I'm trying to teach myself Haskell, and given my imperative background, this is the most mind-warping thing I've had to do in years.
Since there is no Haskell forum here, and really no Haskell forum any place on the internet, I'm posting this in General Programming. I'm sure anyone with any Haskell experience should be able to help with my problem.
Right. I'm trying to write a function cprod to find the cartesian product of a list of lists. For instance,
cprod [[1, 2, 3], [4], [5, 6]] = [[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]
I've got some imperative code that does the job fine in a Pythonesque programming language, so I understand how to solve the problem. However, I don't know how to express it in Haskell's strange syntax, and that's where I need some help.
Here's the imperative code that I know works:
define foo(list, res); if list = nil then return res; endif; for i in hd(list) do foo(tl(list), res + i); endfor; enddefine; [% foo([[1 2 3] [4] [5 6]], []); %]I know that's in a language even more obscure than Haskell (can anyone guess what?), but it should be quite readable.
I'm trying to write that out in Haskell using just recursion for now (so, no fancy foldr or whatever), and this is how far I've gotten so far:
foo list res | list == [] = res | otherwise = [ foo (tail list) (res ++ [x]) | x <- head (head list) ]
That code gives this error when being loaded into Hugs:
ERROR - Type error in application *** Expression : foo2 (tail list) [x] *** Term : tail list *** Type : [[[a]]] *** Does not match : [a] *** Because : unification would give infinite typewhich, unfortunately, means absolutely nothing to me.
Could anyone please prod me in the right direction?
Many thanks,
CChris


Sign In
Create Account

Back to top









