[Haskell-beginners] Simplifying code
Daniel Fischer
daniel.is.fischer at web.de
Wed Feb 10 04:46:03 EST 2010
Am Mittwoch 10 Februar 2010 00:31:07 schrieb Daniel Fischer:
> Am Dienstag 09 Februar 2010 23:07:55 schrieb Patrick LeBoutillier:
> > Daniel,
<snip>
> > One question though: In the docs sequence is described as:
> >
> > "Evaluate each action in the sequence from left to right, and
> > collect the results."
> >
> > How is one supposed to deduce what the behavior will be for the list
> > monad (besides looking at the source)?
<snip>
Or, of course, you could come from the other end.
You want to generate the cartesian product of a list of lists.
How do you do that?
Easy, for each element of the first list, you stick that to the front of
each element of the product of the remaining lists:
cartesianProduct :: [[a]] -> [[a]]
cartesianProduct (l:ls) = [h:t | h <- l, t <- cartesianProduct ls]
-- what to do if there is no first list? The cartesian product of an empty
set of sets is a one element set, so
cartesianProduct [] = [[]]
or,
cartesianProduct (l:ls) = do
h <- l
t <- cartesianProduct ls
return (h:t)
cartesianProduct [] = return []
-- Hey, that's sequence!!!
More information about the Beginners
mailing list