I’m just getting started on monads, and I can’t figure out why these two expressions evaluate differently:
ghci> [1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]
ghci> return ([1,2],['a','b'])
([1,2],"ab")
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The types are different, so it’s reasonable that the behaviors are different
The first expression would typecheck as
Num t => [(t, Char)]The use of [] as the monad in the (>>=) means that it infers that the monad should be the List monad and in the context of the
List Monadhttp://en.wikibooks.org/wiki/Haskell/Understanding_monads/List (>>=) is concatMap and return is (:[]).is the same as
which returns
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]In your second example what’s really going on is
that the type of the expression is a bit more general:
Because you’re running it in GHCi a few things happen. GHCi can be considered a very big special IO Monad. So since no monad was specified, when GHC tries to print the results, it’ll take the
mMonad to beIOin this case.The
tis defaulted toIntegeras well, so the type of the resulting expression is:: IO ([Integer], [Char]).As it happens, all the types used have a
Showinstance, so GHC can print the results of executing theIOaction, which in this case (due to the action being return) is the same as the input.