Ako*_*szi -1 haskell list 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
Run Code Online (Sandbox Code Playgroud)
第二个是棘手的,因为它应该为整个列表返回一个int.我只计算各个元素的字符,而不是整数.
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
Run Code Online (Sandbox Code Playgroud)
对于第二个,您只需要调用sum结果.
countChars xs = sum (map (\w -> length (w)) xs)
Run Code Online (Sandbox Code Playgroud)
也可以改写为
countChars xs = sum $ map length xs
Run Code Online (Sandbox Code Playgroud)
对于第一个,我们必须计算每个元素中的单词数,最后对结果求和.
words会给你一个单词列表,所以在做完之后map (words) xs(不需要用btw的单词括起来),你会得到以下内容:
map words ["asd qwe", "-- Foo", "", "\thello world "]
=>
[["asd","qwe"],["--","Foo"],[],["hello","world"]]
Run Code Online (Sandbox Code Playgroud)
你要做的第一件事是获得每个子列表的长度,你可以适应你的 map
map (\x -> length (words x)) xs
Run Code Online (Sandbox Code Playgroud)
现在,结果是:
[2,2,0,2]
Run Code Online (Sandbox Code Playgroud)
通过对结果运行求和,得到6.所以最终的结果是
countWords :: [String]-> Int
countWords xs = sum $ map (\x -> length (words x)) xs
Run Code Online (Sandbox Code Playgroud)
使用一些语法糖,您可以执行以下操作,但我发现大多数初学者都对此感到困惑:
countWords xs = sum $ map (length . words) xs
Run Code Online (Sandbox Code Playgroud)
甚至更好
countWords = sum . map (length . words)
Run Code Online (Sandbox Code Playgroud)