[Haskell-beginners] Re: List Function
Heinrich Apfelmus
apfelmus at quantentunnel.de
Thu Apr 30 03:57:25 EDT 2009
Edward Z. Yang wrote:
>> However, explaining how/why sequence does this requires understanding
>> the list monad, which you may or may not want to tackle at this point.
>
> Interesting! According to Hoogle, the sequence function evaluates each
> monad and then collects the results. I know evaluating a list monad returns
> a list, but what do they mean by "collect"?
There is also sequence_ which does not collect the results, but throws
them away.
Prelude> sequence_ [ [1,2,3], [4,5,6] ]
[(),(),(),(),(),(),(),(),()]
(Also, concerning terminology, sequence evaluates each monadic action.
You can't evaluate a monad, it's a type constructor, not a function or
value.)
>> If you import 'Control.Applicative' you can even do exactly what you
>> wanted, with pairs and all:
>>
>> Prelude Control.Applicative> liftA2 (,) [1,2,3] [4,5,6]
>> [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
>>
>> Here, liftA2 is applying the function (,) to every possible pair of
>> values from the two lists.
>
> I'm not even going to try to understand that now.
Also known as
liftM2 (,) [1,2,3] [4,5,6]
Which is the same as
do
x <- [1,2,3]
y <- [4,5,6]
return (x,y)
Regards,
apfelmus
--
http://apfelmus.nfshost.com
More information about the Beginners
mailing list