在Haskell中将列表追加到列表列表中? [英] Appending lists into a list of lists in Haskell?
问题描述
在文档中我所能找到的全部是++和concat.
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]
但是您知道,仅给出[1,2,3,4,5,6].
but as you know that just gives [1, 2, 3, 4, 5, 6].
我需要做什么来接受[1、2、3]和[4、5、6]并退出[[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]]
但这只是(:)
,
push = (:)
正如注释中所提到的,值[x,y]
也可以写为x : y : []
. 1 由于这两种情况都可以用(:)
完成,所以我猜想您实际上是想要使用的是(:)
,有时包含在[]
上,有时包含在非空列表中.
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 实际上,[x,y]
只是语法糖用于x:y:[]
.
这篇关于在Haskell中将列表追加到列表列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!