Monad 与顺序函数调用
Monad vs sequential function calls
Wikipedia article on monads 说:
Purely functional programs can use monads to structure procedures that include sequenced operations like those found in structured programming.
不是在这里寻找(另一个)monad 教程。请举一个 monad 的例子,当仅仅 运行ning 一个函数然后另一个是不够的时候使顺序操作成为可能。根据功能语言规范,它是否与那些懒惰的函数调用有某种联系?为什么顺序 运行 的不互换功能需要任何 "wrapper"?
Haskell Monad Tutorial 清楚地显示了以单子方式对函数调用进行排序的示例:
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
Wikipedia article on monads 说:
Purely functional programs can use monads to structure procedures that include sequenced operations like those found in structured programming.
不是在这里寻找(另一个)monad 教程。请举一个 monad 的例子,当仅仅 运行ning 一个函数然后另一个是不够的时候使顺序操作成为可能。根据功能语言规范,它是否与那些懒惰的函数调用有某种联系?为什么顺序 运行 的不互换功能需要任何 "wrapper"?
Haskell Monad Tutorial 清楚地显示了以单子方式对函数调用进行排序的示例:
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