简体   繁体   中英

Appending lists into a list of lists in Haskell?

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]]?

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:[] .

think about what the (++) operator does: it concatenates Lists, it does not construct them. This is how it concatenates text Strings into a new String (and not a list of Strings), since Strings are lists of Chars. to construct a new List out of Lists you use (:) like so:

[1,2,3]:[4,5,6]:[]

where youre adding each list as an element of a new list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM