Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

Interpreting Haskell monad example

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+))

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+)) 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can rewrite equivalent triple2 function as follows:

triple2 = (id >>= (
 -> (n+))) >>= (d -> (d+))

With f = -> (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


 -> f (id r) r = 
 -> f r r = 
 -> (r+) r

2. (id >>= f) >>= f

x = id >>= f = 
 -> (r+) r
x r = (r+) r
x >> f = 
 -> f (x r) r = f ((r+) r) r = ((r+) r)+ r

so ((10+) 10)+ 10 makes 30


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...