How can I add a List to another, returning a List of Lists?
foo :: [a] -> [a] -> [[a]]
For example, my desired result of:
foo [1,2] [3,4]
would be [[1,2], [3,4]]
.
++
didn't work:
*Main> [1,2] ++ [3,4]
[1,2,3,4]
Surely just this would work?
foo :: [a] -> [a] -> [[a]]
foo a b = [a, b]
[a, b]
is sugar for a : b : []
; so if you ever need something more general you can use (:[])
to create a singleton list and (:)
to prepend further elements. If you want to confuse people you can even write foo
pointfree as foo = (.(:[])).(:)
(:[])
? Prelude> (:[]) : 3
isn't working` in REPL.
May 2, 2014 at 18:44
(:[])
is a function, since (:)
is an infix function a -> [a] -> [a]
and its right argument is []
we get a new function (:[])
with type a -> [a]
. You can apply this to anything to put it in a singleton list, e.g. (:[]) 5 = [5]
It is a bit funny that you almost wrote the answer to your question yourself:
foo [1,2] [3,4] would be [[1,2], [3,4]].
Now, all you need to do mentally is to abstract from concrete example values! Replace [1,2]
with a
and [3,4]
with b
for example. Then you can tell Haskell that you want
foo a b = [a, b]
And that is it! Although it has a more general type than what you intended.