Reputation: 595
What is the type and the value of the expression:
do [1,2,3]; "lambda"
I tested it and found out that it just print lambda 3 times. But i don't understand why it does that. how can i rewrite it using bind. It feels like it is necessary to rewrite it.
Upvotes: 2
Views: 133
Reputation: 71119
by definition of list monad,
do [1,2,3]; "lambda" -- "lambda" = ['l','a','m','b','d','a']
= [1,2,3] >>= (\x -> "lambda")
= [r | x <- [1,2,3], r <- "lambda"]
for list monad return x = [x]
, and so the usual use-case of
do x <- [1,2,3]; return x
= [r | x <- [1,2,3], r <- [x]]
gets shortcut into just [x | x <- [1,2,3]]
. This uses the monad law m >>= return = m
.
But the last monadic value in a do
sequence, of type m a
(here, [a]
), doesn't have to be a singleton list. It can be empty, or hold several elements.
As for the type of the result, it is [Char]
. First of all, do
represents a bind chain, and the type of bind is
(>>=) :: m a -> ( a -> m b) -> m b
Since in your example the monadic values are lists, we conclude that m = []
. The last value is of type String
which is [Char]
, and so according to the above signature, this is the type of the result.
Upvotes: 0
Reputation: 33691
Your code is the same as
[1, 2, 3] >> "lambda"
>>
is defined as
m >> n = m >>= \_ -> n
And >>=
operator is defined for lists as:
xs >>= f = concat (map f xs)
So, your code may be translated into:
concat $ map (const "lambda") [1, 2, 3]
Which produces the result
"lambdalambdalambda"
Upvotes: 6
Reputation:
here is the same output with bind:
λ> [1,2,3] >>= \x -> "lambda"
"lambdalambdalambda"
What did you expect to get?
Upvotes: 0