假设F是一个具有附加定律的应用函子(使用Haskell语法):
pure (const ()) <*> m === pure ()pure (\a b -> (a, b)) <*> m <*> n === pure (\a b -> (b, a)) <*> n <*> mpure (\a b -> (a, b)) <*> m <*> m === pure (\a -> (a, a)) <*> m如果省略(3.),所谓的结构是什么?
我在哪里可以找到有关这些法律/结构的更多信息?
满足(2.)的函数通常被称为可交换的.
现在的问题是,(1.)是否暗示(2.)以及如何描述这些结构.我对满足(1-2.)但不满足(3.)的结构特别感兴趣
例子:
F给出的monad 满足(1-2.)但不满足(3.)定义F:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
import Control.Monad.State
newtype X i = X Integer deriving …Run Code Online (Sandbox Code Playgroud) Control.Monad.ST在base包中包含runST运行严格的状态变换器monad:
runST :: (forall s. ST s a) -> a
Run Code Online (Sandbox Code Playgroud)
但是,我需要一个通用版本runST:
runSTCont :: (forall s . (forall b . ST s b -> b) -> a) -> a
runSTCont f = f $ \m -> runST $ unsafeCoerce m
Run Code Online (Sandbox Code Playgroud)
我的问题是:这是否unsafeCoerse安全使用?(我想是的,因为据我所知,索引的唯一目的s是防止s在结果中泄漏索引值a.runSTCont不能泄漏s索引值的类型,所以应该没问题.)
请注意,runST在来表示runSTCont这样runSTCont至少一般为runST:
runST' :: (forall s. ST s a) -> a
runST' m = …Run Code Online (Sandbox Code Playgroud) 我想选择中止一个getChar动作.我需要以下功能:
getChar' :: (Char -> IO ()) -> IO (IO ())
Run Code Online (Sandbox Code Playgroud)
如果是abort <- getChar' callback,则从标准输入读取字符,除非abort在字符可用之前调用.如果读取了一个字符,callback则使用它进行调用.
我有以下原型实现:
import Control.Monad
import Control.Concurrent
getChar' :: (Char -> IO ()) -> IO (IO ())
getChar' callback = do
v <- newEmptyMVar
tid <- forkIO $ do
c <- getChar
b <- tryPutMVar v ()
when b $ callback c
return $ do
b <- tryPutMVar v ()
when b $ killThread tid
Run Code Online (Sandbox Code Playgroud)
问题是killThread可能在读取char之后但在放入() …