在 Haskell 中结合地图和长度

Combining map and length in Haskell

我在使用 map 和 length 时遇到了两个问题 第一个应该给我返回字数,但它只计算列表中的元素。

countWords :: [String]-> Int
countWords xs = length (map (words) xs)

countWords ["asd  qwe", "-- Foo", "", "\thello world "] => 4--instead it have six words

第二个比较棘手,因为它应该为整个列表返回一个整数。我只能统计单个元素的字符数,不能统计全部。

countChars :: [String]-> [Int] --it should be Int
countChars xs = map (\w -> length (w)) xs 

countChars ["asd  qwe", "-- Foo", "", "\thello world "] => [8,6,0,13]--it should give back the sum of this list which is 27

对于第二个,你只需要对结果调用sum

countChars xs = sum (map (\w -> length (w)) xs)

也可以改写为

countChars xs = sum $ map length xs 

对于第一个,我们必须计算每个元素中的单词数,最后将结果相加。

words 会给你一个单词列表,所以在做 map (words) xs 之后(顺便说一句,不需要在单词周围加上括号),你会得到以下内容:

map words ["asd  qwe", "-- Foo", "", "\thello world "] 
=> 
[["asd","qwe"],["--","Foo"],[],["hello","world"]]

您要做的第一件事是获取每个子列表的长度,您可以将其放入 map

map (\x -> length (words x)) xs

现在,结果是:

[2,2,0,2]

然后运行对结果求和,得到6。所以最终结果是

countWords :: [String]-> Int
countWords xs = sum $ map (\x -> length (words x)) xs

使用一些语法糖,您可以执行以下操作,但我发现大多数初学者对此感到困惑:

countWords xs = sum $ map (length . words) xs

甚至更好

countWords = sum . map (length . words)