也许单子建筑 [英] Maybe monad construction
问题描述
我目前正在为Haskell的一个新元素而苦苦挣扎:Monads.因此,通过创建(>>=)
运算符的示例向我介绍了此示例,该运算符仅在不等于Nothing
的情况下以Maybe
类型(以其实际整数值作为参数)执行函数,否则返回Nothing
:
I'm currently struggling with a new element of Haskell: Monads. Therefore I was introduced to this by an example of creating a (>>=)
operator that executes a function on a Maybe
type (taking its actual integer value as argument to it) only if it's not equal to Nothing
, and otherwise return Nothing
:
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ = Nothing
(Just x) >>= f = f x
但是,我不太确定如何配合以下用法使用它:
However, I'm not quite sure how this works with the following usage of it:
eval (Val n) = Just n
eval (Div x y) = eval x >>= (\n ->
eval y >>= (\m ->
safediv n m))
在我看来,(>>=)
运算符仅采用一个Maybe
值,然后返回一个函数,但是在此示例用法代码中,它似乎采用了2倍的Maybe
值和一个函数.有人告诉我,它会评估x
,将结果放入n
,然后评估y
,将结果放入y
,然后在两者上执行safediv
函数.尽管我在这里看不到(>>=)
运算符如何发挥作用;这是如何运作的?
It seems to me that the (>>=)
operator simply takes one Maybe
value and a function that returns one, however in this example usage code it seems like it's taking 2 times a Maybe
value and once a function. I was told however that it evaluates x
, puts the result in n
, then evaluates y
, puts the result in y
, and then executes the safediv
function on both. Although I don't see how the (>>=)
operator plays its role here; How does this work?
推荐答案
您可以这样阅读:
eval (Div x y) = eval x >>= (\n ->
eval y >>= (\m ->
safediv n m))
想要的时候eval (Div x y)
然后
- 第一个
eval x
: -
- 如果是
Just n
(使用第一个>> = )
- first
eval x
: - if was
Just n
(using the first >>=)
- 然后使用
n
并查看eval y
(使用第一个>> = )
- then take the
n
and have a look ateval y
(using the first >>=)
-
- 如果最后一个是
Just m
(第二个>> = )
- if the last is
Just m
(second >>=)
-
- 然后使用
m
并执行(第二个>> = )
- then take the
m
and do a (second >>=)
-
-
savediv n m
返回结果-闭包中仍然有n
!
savediv n m
to return it's result - you still have then
from your closure!.
在其他情况下,返回
Nothing
所以在这里
(>>=)
只是帮助您解构.So here the
(>>=)
just helps you to deconstruct.也许以
do
形式更容易阅读和理解:Maybe it's easier to read and understand in the
do
form:eval (Val n) = Just n eval (Div x y) = do n <- eval x m <- eval y safediv n m
这只是
(>>=)
eval x >>= (...) = Nothing >>= (...) = Nothing
2.
eval x = Nothing
和eval y = Just n
:这是相同的:
2.
eval x = Nothing
andeval y = Just n
:which is just the same:
eval x >>= (...) = Nothing >>= (...) = Nothing
3.
eval x = Just n
和eval y = Nothing
:eval x >>= (\n -> eval y >>= (...)) = Just n >>= (\n -> eval y >>= (...)) = Just n >>= (\n -> Nothing) = Nothing
4.
eval x = Just n
和eval y = Just m
:eval x >>= (\n -> Just m >>= (...)) = Just n >>= (\n -> Just m >>= (...)) = Just n >>= (\n -> Just m >>= (\m -> safediv n m)) = (first >>= for Just) = Just m >>= (\n -> safediv n m) = (second >>= for Just) = safediv n m
这篇关于也许单子建筑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-
- then take the
- 然后使用
- if the last is
- 如果最后一个是
- if was
- 如果是