Appending lists into a list of lists in Haskell?

10,467

As mentioned in comments, a function to take two lists and combine them into a new list can be defined as:

combine :: [a] -> [a] -> [[a]]
combine xs ys = [xs,ys]

This function can't be applied multiple times to create a list of an arbitrary number of lists. Such a function would take a single list and a list of lists and it would add the single list to the list of lists, so it would have type:

push :: [a] -> [[a]] -> [[a]]

This is just (:), though:

push = (:)

As also mentioned in the comments, the value [x,y] can also be written as x : y : [].1 Since both cases can be done with (:), I would guess that what you really want to use is (:), sometimes consing onto [] and sometimes onto a non-empty list.


1 In fact, [x,y] is just syntactic sugar for x:y:[].

Share:
10,467
Stumbleine75
Author by

Stumbleine75

Updated on June 04, 2022

Comments

  • Stumbleine75
    Stumbleine75 almost 2 years

    All I've been able to find in the documentation that are relevant are ++ and concat.

    I thought at first doing the following would give me what I wanted:

      [1, 3, 4] ++ [4, 5, 6]
    

    but as you know that just gives [1, 2, 3, 4, 5, 6].

    What would I need to do to take in [1, 2, 3] and [4, 5, 6] and get out [[1, 2, 3], [4, 5, 6]]?