【发布时间】:2014-04-03 00:53:24
【问题描述】:
在试图找到一个可以逐步执行/允许线程的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 和 (<*>) = ap 的应用函子。
对我来说,应用函子在概念上比单子更难。为了更好地理解 applicative functors,我喜欢在不诉诸 ap 的情况下拥有 applicative 实例。
<*> 的第一行很简单:
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
fmap和<*>如何在基本术语中定义Roll f <*> x?
【问题讨论】:
标签: haskell applicative free-monad