在Haskell中组合地图和长度

时间:2018-11-25 07:59:01

标签: list haskell map-function

我在使用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

1 个答案:

答案 0 :(得分:5)

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

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

也可以改写为

countChars xs = sum $ map length xs 

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

words将为您提供单词列表,因此在完成map (words) xs(不需要在单词btw后面加上括号)之后,您将获得以下信息:

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)