This is probably a very noob question but I was playing around with the bind operator in Haskell and I encountered a way to repeat a string using it.
[1..3] >>= const "Hey"
-- Yields "HeyHeyHey"
[1..3] >>= return "Hey"
-- Also yields the same result
I understand how >>= (\_ -> return "Hey")
would yield ["Hey", "Hey", "Hey"]
but I don't understand why (\_ -> "Hey")
repeats the string or why >>= return "Hey"
does the same thing.
I understand how
>>= (\_ -> return "Hey")
would yield["Hey", "Hey", "Hey"]
right. return "Hey"
is in this case the same as ["Hey"]
, because
instance Monad [] where
return x = [x]
So
([1..3] >>= \_ -> return "Hey")
≡ ([1..3] >>= \_ -> ["Hey"])
≡ ["Hey"] ++ ["Hey"] ++ ["Hey"]
≡ ["Hey", "Hey", "Hey"]
Now, >>= (\_ -> "Hey")
can also be be written with a list-result in the lambda, because strings are just lists of characters.
([1..3] >>= \_ -> "Hey")
≡ ([1..3] >>= \_ -> ['H','e','y'])
≡ ['H','e','y'] ++ ['H','e','y'] ++ ['H','e','y']
≡ ['H','e','y','H','e','y','H','e','y']
≡ "HeyHeyHey"
As for >>= return "Hey"
, that's a different beast. The return
belongs to a completely different monad here, namely the function functor.
instance Monad (x->) where
return y = const y
Hence it's kind of clear that ([1..3] >>= const "Hey")
and ([1..3] >>= return "Hey")
give the same result: in that example, return
is just another name for const
!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments