【发布时间】:2014-05-27 17:52:48
【问题描述】:
我在 C# 中实现了我自己的 Promise 结构,并想在 Haskell 中测试这个概念,所以经过一些严格的大脑锻炼(对此仍然很新)我制作了
data Promise f a = PendingPromise f | ResolvedPromise a | BrokenPromise deriving( Show )
class Future p where
later :: (b -> c) -> p (a -> b) b -> p (a -> c) c
resolve :: p (a -> b) a -> a -> p (a -> b) b
instance Future Promise where
later g (PendingPromise f) = PendingPromise (g . f)
later g (ResolvedPromise a) = ResolvedPromise (g a)
resolve (PendingPromise f) a = ResolvedPromise (f a)
弄清楚如何编写此数据类型Promise f a 真是令人头疼。
无论如何,later 方法似乎是某种 Applicative Functor 和 Promises 应该是 Monads。我是否可以将 Promise 设为某个 class 的实例并获得此功能,而不是实现我自己的 Future 类?
编辑
感谢@bheklilr,later 函数被证明是 fmap,只是对数据类型进行了一点重新定义
data Promise a b = PendingPromise (a -> b) | ResolvedPromise b | BrokenPromise
instance Functor (Promise c) where
fmap f (PendingPromise g) = PendingPromise (f . g)
fmap f (ResolvedPromise a) = ResolvedPromise (f a)
fmap f BrokenPromise = BrokenPromise
知道 (Promise a) 是 Functor,就更容易理解为什么是 Monad。
【问题讨论】:
-
每个 Monad 都是 Applicative。
标签: haskell