解释Haskell monad的例子 [英] Interpreting Haskell monad example
问题描述
triple :: Int - >我有这个Haskell代码可以三元输入值。 Int
triple = do
n < - id
d < - (n +)
(d +)
这段代码如何工作?例如 triple 10
,参数 10
如何映射/分配给 id
,
n
和 d
得到30的返回值?
我的理解如下:
我们可以用两个子函数分解 triple
函数 tripleA
和 tripleB
如下:
triple :: Int - > Int
triple = tripleA>> =(\ d - > tripleB d)
tripleA :: Int - > Int
tripleA = id>> =(\ n - >(n +))
tripleB :: Int - > Int - > Int
tripleB d =(d +)
现在我们可以看到函数 tripleA
获取一个输入,将它分配给 id
函数以返回值本身,并将其映射到函数(\ n - >(n +))
返回(10+)10
。
同样,tripleB也使得(20+)20
,所以我期望结果为40,但正确答案为30。
$ b
我的解释有什么问题?
我们可以像下面这样重写等价的triple2函数:
triple2 =(id>> =(\ n - >(n +)))>> = (\d->(d +))
使用 f = \\ \\ n - > (n +)
,我们有 triple2 =(id>> f)>> f
。
从>> =
in(),我们有
1。 id >> = f
\r - > f(id r)r = \ r - > f r r = \ r - > (r +)r
2。 (id >> = f)>> = f
x = id>> = f = \r - > ; (r +)r
x r =(r +)r
x>> f = \ r - > f(xr)r = f((r +)r)r =((r +)r)+ r
< > ((10+)10)+ 10
使
I have this Haskell code that triples input value.
triple :: Int -> Int
triple = do
n <- id
d <- (n+)
(d+)
How does this code work? With an example triple 10
, how the argument 10
is mapped/assigned to id
, n
and d
to get the return value of 30?
My understandig is as follows:
We can decompose triple
function with two subfunctions tripleA
and tripleB
as follows:
triple :: Int -> Int
triple = tripleA >>= (\d -> tripleB d)
tripleA :: Int -> Int
tripleA = id >>= (\n -> (n+))
tripleB :: Int -> Int -> Int
tripleB d = (d+)
Now we can see that the function tripleA
gets an input, assign it to id
function to return the value itself, and map it to the function (\n -> (n+))
to return (10+) 10
.
Likewise, tripleB also makes (20+) 20
, so I expect the results as 40, but the correct answer is 30.
What is wrong with my interpretation?
We can rewrite equivalent triple2 function as follows:
triple2 = (id >>= (\n -> (n+))) >>= (\d -> (d+))
With f = \n -> (n+)
, we have triple2 = (id >> f) >> f
.
From the definition of >>=
in (https://hackage.haskell.org/package/base-4.9.0.0/docs/src/GHC.Base.html#line-645), we have
1. id >>= f
\r -> f (id r) r = \r -> f r r = \r -> (r+) r
2. (id >>= f) >>= f
x = id >>= f = \r -> (r+) r
x r = (r+) r
x >> f = \r -> f (x r) r = f ((r+) r) r = ((r+) r)+ r
so ((10+) 10)+ 10
makes 30
这篇关于解释Haskell monad的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!