在尝试找到可以逐步执行/允许线程的haskell monad时,我发现了免费的monad
data Free f a = Return a | Roll (f (Free f a))
及其 monad 实例
instance (Functor f) => Monad (Free f) where
return = Return
Return x >>= f = f x
Roll action >>= f = Roll $ fmap (>>= f) action
及其函子实例
instance (Functor f) => Functor (Free f) where
fmap f (Return x) = Return (f x)
fmap f (Roll x) = Roll $ fmap (fmap f) x
我知道每个 monad 都是一个带有pure = return
and的应用函子(<*>) = ap
。对我来说,应用函子在概念上比单子更难。为了更好地理解应用函子,我喜欢使用应用实例而不使用ap
.
第一行<*>
很简单:
instance (Applicative f) => Applicative (Free f) where
pure = Return
Return f <*> x = fmap f x -- follows immediately from pure f <*> x = f <$> x
--Roll f <*> x = Roll $ (fmap ((fmap f) <*>)) x -- wrong, does not type-check
如何用和定义Roll f <*> x
基本术语?fmap
<*>