简体   繁体   English

将列表添加到Haskell中的列表列表中

[英]Add a list to a list of lists in Haskell

How can I add a list to a list of lists? 如何将列表添加到列表列表? Say I want to add itemz to bagList , which is a list of lists. 假设我要将itemz添加到bagList ,这是一个列表列表。 How can I do that? 我怎样才能做到这一点?

bagList itemz = mappend bagList itemz               

You might want to consider adding it at the front, this is faster: 您可能需要考虑将其添加到前面,这样速度更快:

bagItem bag item = item : bag

Also it looks like you're coming from an imperative mindset, the way you use bagList before and after the = is not quite right: the expressions before and after the = do not really represent the same construction. 而且看起来您来自命令式思维,在=之前和之后使用bagList的方式不太正确: =之前和之后的表达式实际上并不能表示相同的构造。 Before the = bagItem is used as a function, after the = it's used as some Monoid (which if itemz is a list would also need to be a list). 在将= bagItem用作函数之前,在=之后将其用作某些Monoid (如果itemz是列表,则也需要作为列表)。

If you really do want to append the item (this will be slower, because the operation will require going all the way through the list to add the new item at the end, and the whole list will need to be reconstructed) you can do what Christoph suggests or you can go for a recursive formulation something like this: 如果您确实确实想追加项目(这样做会比较慢,因为操作将需要遍历列表以在末尾添加新项目,并且整个列表都需要重建),您可以执行以下操作克里斯托夫(Christoph)建议,或者您可以采用如下递归公式:

appendItem :: a -> [a] -> [a]
appendItem i (x:xs) = x : appendItem i xs
appendItem i [] = i : []

If you both want to append and are also worried about performance, you should have a look at difference lists, for example look for the section on difference lists in this chapter in Learn You a Haskell . 如果您既想追加内容又对性能感到担忧,则应该查看差异列表,例如, 在“了解您的Haskell”中查找本章中差异列表中的部分。


Update 更新资料

From the comments it seems what you are actually looking for is Map s. 从评论看来,您实际上真正想要的是Map We can make a Map with each item as a key, and the number of occurrences as the value. 我们可以创建一个Map ,将每个项目作为键,并将出现次数作为值。 In your case it seems this will be a Map String Int . 在您的情况下,这似乎是Map String Int

import Data.List (foldl')
import qualified Data.Map as M

bag :: M.Map String Int
bag = M.empty

addToBag :: M.Map String Int -> [String] -> M.Map String Int
addToBag = foldl' go
  where go m i = M.insertWith (+) i 1 m

main = print $ addToBag bag ["a","b","c","a"]
-- fromList [("a",2), ("b", 1), ("c", 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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