Herokiller
Herokiller

Reputation: 2991

Undestanding how cartesian product implementation on Haskell works

I have started learning Haskell and I have problem with understanding how cartesian product of lists of the list works

here is the supposed code

cprod = foldr f [[ ]]
      where f xs yss = foldr g [ ] xs
            where g x zss = foldr h zss yss
                  where h ys uss = (x : ys) : uss

What exactly I don't get is the last function I've replaced variable names as I understand it

mycart = foldr f [[]]
    where f currentresult listelem = foldr g [] currentresult
          where g currentresultonstep currentresultelem = foldr h currentresultelem listelem
                where h currentresultelemonstep onelistelem = (currentresultonstep:currentreslteleemonstep):onelistelem

Shouldn't the last string be something like this?

where h currentresultelemonstep onelistelem = (onelistelem:currentresultelemonstep):currentresultonstep

as we try to add the elements of the list to the beginning on elements of current result ?

Upvotes: 0

Views: 294

Answers (1)

melpomene
melpomene

Reputation: 85757

First off, your code as written isn't syntactically valid:

foo.hs:3:13: parse error on input `where'

Second, it seems like you're confused about the order of arguments in the first parameter of foldr:

foldr :: (a -> b -> b) -> b -> [a] -> b

The first argument (a) is an element of the input list ([a]), the second argument (b) is the accumulator.

Upvotes: 3

Related Questions