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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…