[Haskell-beginners] List Function

Joe Fredette jfredett at gmail.com
Wed Apr 29 22:39:18 EDT 2009


So, two ways you could do it.

I assume your current function looks like:

    toPairs :: [a] -> [a] -> [[a]]
    toPairs [] _ = []
    toPairs (x:xs) ls = (zip (\y -> (x,y)) ls) : (toPairs xs ls)

This returns something like:

    toPairs [1,2] [3,4] ===> [[(1,3),(1,4)],[(2,3),(2,4)]]

We want a function that takes this list-of-lists to a list. We can 
certainly see the type as:

    foo :: [[a]] -> [a]

`foo` would have to take all the elements of each list, and put it in a 
new one. We know of a function which combines the elements of two lists, 
(++)
so really, our foo function would do:

foo [] = []
foo (x:xs) = x ++ foo xs

concatenating all of the lists together in order. But this is just a 
fold, we can call foo:

foo = foldr (++) -- or foldl would work too.

foldr is just the pattern above, abstracted away to a convenient function.

Of course, this function comes up all the time, so we have one in the 
prelude, it's called. `concat`. and if you look up the source on hoogle, 
I believe you'll find the above.

Nathan Holden wrote:
> I don't know what you'd call it. Is there a function in any of the 
> basic functions that does this something like this:
>
> Sending two lists, [1,2,3] and [2,3,4] it would return 
> [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]. I managed to 
> code my way into returning a list of lists, which works. But it seemed 
> like a very basic list/matrix function, so I honestly believe that the 
> Haskell designers probably would've put it in.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>   
-------------- next part --------------
A non-text attachment was scrubbed...
Name: jfredett.vcf
Type: text/x-vcard
Size: 296 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/beginners/attachments/20090429/e6863019/jfredett.vcf


More information about the Beginners mailing list