哈斯克尔期待的类型麻烦

mom*_*omi 0 haskell types

Haskell的新功能和功能编程......在学习过程中.这段代码有什么问题:

import System.IO
import Data.Char
import System.Environment

main = do
   args <- getArgs
   progName <- getProgName
   content <- readFile $ head args
   putStrLn $ show $ getWordsInfo content

getWordsInfo = let
                  wordList = filter (\x -> length x > 2 && all isAlpha x) . words
               in foldl foldingFunction 0 wordList
                 where foldingFunction acc tWord = acc + length tWord
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,我得到以下内容

 Couldn't match expected type `[[a0]]'
            with actual type `String -> [[Char]]'
In the third argument of `foldl', namely `wordList'
In the expression: foldl foldingFunction 0 wordList
In the expression:
  let
    wordList = filter (\ x -> length x > 2 && all isAlpha x) . words
  in foldl foldingFunction 0 wordList
Run Code Online (Sandbox Code Playgroud)

Zpa*_*ree 5

您似乎错误地使用了无点符号.

这个错误的唯一一行是:

let wordList = filter (\x -> length x > 2 && all isAlpha x) . words

错误消息是,当您调用wordList时,它尚未应用于足够的参数,它期望列表列表,而是给出了一个函数,该函数接受一个字符串并生成一个列表列表.所以,我们只需要给wordList函数输入字符串.

你可以用两种方式重写它:

第一种是通过显式指定参数:

getWordsInfo xs = let wordList = filter (\x -> length x > 2 && all isAlpha x) (words xs)
                  in foldl foldingFunction 0 wordList
                    where foldingFunction acc tWord = acc + length tWord
Run Code Online (Sandbox Code Playgroud)

第二个是保持点空闲位不在let绑定中:

getWordsInfo = foldl foldingFunction 0 . filter (\x -> length x > 2 && all isAlpha x) . words
                    where foldingFunction acc tWord = acc + length tWord
Run Code Online (Sandbox Code Playgroud)

你的折叠函数取每个单词的长度并将它们相加,可以通过映射列表,取长度,然后对列表求和来简化.

getWordsInfo = sum . map length . filter (\x -> length x > 2 && all isAlpha x) . words
Run Code Online (Sandbox Code Playgroud)

这条线路有点长,所以我们应该将其中的一部分考虑到另一个定义中,最后给出我们:

import Data.Char (isAlpha)

getWordsInfo = sum . map length . filter isLongWord . words
    where isLongWord x = length x > 2 && all isAlpha x
Run Code Online (Sandbox Code Playgroud)

用法:

?> getWordsInfo "apple banana orange a a b b punctuation!!"
17
?> getWordsInfo "aa bb cc"
0
?> getWordsInfo "!!!"
0
?> getWordsInfo "apple"
5
?>
Run Code Online (Sandbox Code Playgroud)