纯粹的功能程序可以使用monad来构建程序,其中包括结构化编程中的顺序操作。
不在这里寻找(另一个)monad教程。请举例说明monad在运行一个函数时可能使顺序操作成为可能,然后另一个函数是不够的。是否以某种方式连接那些函数调用是否是每个函数式语言规范的延迟?为什么顺序运行不互换的函数需要任何"包装器"?
答案 0 :(得分:4)
Haskell Monad Tutorial清楚地显示了以monadic方式对函数调用进行排序的示例:
type Sheep = ...
father :: Sheep -> Maybe Sheep
father = ...
mother :: Sheep -> Maybe Sheep
mother = ...
-- comb is a combinator for sequencing operations that return Maybe
comb :: Maybe a -> (a -> Maybe b) -> Maybe b
comb Nothing _ = Nothing
comb (Just x) f = f x
-- now we can use `comb` to build complicated sequences
mothersPaternalGrandfather :: Sheep -> Maybe Sheep
mothersPaternalGrandfather s = (Just s) `comb` mother `comb` father `comb` father