我正在用JavaScript实现Maybe
(又名Option
)类型的monad转换器(请注意,我使用类型词典传递):
const optOfT = of => x =>
of(optOf(x));
const optMapT = map => f => ttx =>
map(optMap(f)) (ttx);
const optApT = chain => ttf => ttx =>
chain(tf =>
chain(tx =>
optAp(tf) (tx)) (ttx)) (ttf);
const optChainT = chain => fm => mmx =>
chain(mx =>
optChain(fm) (mx)) (mmx);
(映射〜{<$>
,ap〜<*>
,链〜=<<
,= =纯/返回)
虽然此代码有效,但我想知道是否可以在没有外部monad的monad约束的情况下实现optApT
。我偶然发现了这个Haskell示例:
(<<**>>) :: (Applicative a, Applicative b) => a (b (s -> t)) -> a (b s) -> a (b t)
abf <<**>> abs = pure (<*>) <*> abf <*> abs
这似乎正是我想要的,但是我无法识别pure (<*>) <*> abf <*> abs
的评估顺序以及哪个<*>
运算符属于哪个应用层:
const optApT = (ap, of) => ttf => ttx =>
...?
任何提示都值得赞赏。
答案 0 :(得分:2)
希望这对您有帮助...
以下是与各种类型类函数关联的类型:
abf <<**>> abs = pure (<*>) <*> abf <*> abs
(4) (3) (2) (1)
(1), (2): the `ap` for type a
(3): the `ap` for type b
(4): the `pure` for type a
评估顺序为:
(pure (<*>)) <*> abf <*> abs