[英]Haskell monads and the do statement
I'm new to monads and its use and the following structure using the do-statement had me quite confused: 我是monads的新手,它的使用以及使用do语句的以下结构使我非常困惑:
pairs xs ys = do x <- xs
y <- ys
return (x, y)
I was told this should return all possible pairs of x and y, which I do not understand because I was earlier taught that the following code: 有人告诉我这应该返回x和y的所有可能的对,我不明白,因为我之前被告知以下代码:
eval (Val n) = Just n
eval (Div x y) = do n <- eval x
m <- eval y
safediv n m
means: execute eval x
, then keep its result if not equal to Nothing
(otherwise return Nothing) as n
, then the same for eval y
, and then if both are not Nothing
it will proceed to the final function safediv
that combines both results (and otherwise return Nothing
too). 意思是:执行
eval x
,然后如果不等于Nothing
(否则返回Nothing)为n
,则保持其结果,然后对eval y
保持相同,然后如果两者都不为Nothing
,它将继续执行将两个结果safediv
的最终函数safediv
(否则返回Nothing
)。
However the 1st use of the do-statement in the function pairs
works totally different? 但是在函数
pairs
第一次使用do语句的工作原理完全不同吗?
If someone could help me out on this and explain what's the actually proper functionality of the do-statement and its structure, it'd be much appreciated! 如果有人可以帮助我解决这个问题,并解释do语句及其结构的真正适当功能,将不胜感激!
Best regards, Skyfe. 最好的问候,Skyfe。
The do
construct works in any monad, and there you are using it in two different monads. do
构造可在任何 monad中使用,并且在两个不同的monad中使用它。
In the first case, 在第一种情况下,
pairs xs ys = do x <- xs
y <- ys
return (x, y)
you are working in the list monad, ie []
. 您正在使用monad列表,即
[]
。 You can see that because you use x <- xs
and xs
is of type [something]
. 可以看到,因为使用
x <- xs
并且xs
的类型为[something]
。
In the second case 在第二种情况下
eval (Val n) = Just n
eval (Div x y) = do n <- eval x
m <- eval y
safediv n m
you are working in the Maybe
monad. 您正在
Maybe
monad工作。 Indeed, you use y <- eval x
and eval
returns Maybe something
. 确实,您使用
y <- eval x
并且eval
返回Maybe something
。
Each monad defines its own rules about what <-
should mean. 每个monad都定义其有关
<-
含义的规则。 In the list monad, it roughly means "consider all possible elements", in the Maybe one "take the x
in Just x
, and fail otherwise". 在列表单子,它大致的意思是“考虑所有可能的因素”,在也许有“拿
x
中Just x
,否则失败。”
Technically, the <-
construct within a do
is desugared into a call to the >>=
operator, which every monad defines independently. 从技术上讲,
do
的<-
构造被减为对>>=
运算符的调用,每个monad独立定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.