Haskell解析错误'让'

时间:2018-04-11 05:58:29

标签: haskell

嘿,我遇到了解析错误的问题,我对此很陌生。 Haskell的白色空间规则在做什么和让我们找不到时,我找不到多少。如果你能指出我正确的方向,那将非常感激。

CODE:

import Data.Char

-- shorterThan function takes a filename and a length and returns all words in the file shorter than the given length.

shorterThan :: String -> Int -> IO [String]
shorterThan fileName len = do fileContents <- readFile fileName
                                let fileWords = lines fileContents
                                let shorterThanWords = [word | word <- fileWords, (length word) < len]
                                return shorterThanWords

shorterThan' :: String -> Int -> IO [String]
shorterThan' fileName len = readFile fileName >>= (\fileContents -> let fileWords = lines fileContents
                                                                        shorterThanWords = [word | word <-fileWords, (length word) < len]
                                                                    in return shorterThanWords))

1 个答案:

答案 0 :(得分:4)

您的do-block未正确缩进。这是一种方式:

shorterThan :: String -> Int -> IO [String]
shorterThan fileName len = do
  fileContents <- readFile fileName
  let fileWords = lines fileContents
  let shorterThanWords = [word | word <- fileWords, length word < len]
  return shorterThanWords

let必须从do-block缩进开始。

最近你也有一个)太多了。

我更喜欢将“短于”逻辑分成非I / O函数,如下所示:

shorterThan :: Int -> [String] -> [String]
shorterThan n ws = [ w | w <- ws, length w < n ]

wordsFromFile :: FilePath -> IO [String]
wordsFromFile filePath = words <$> readFile filePath

main :: IO ()
main = wordsFromFile "hello.txt" >>= mapM_ putStrLn . shorterThan 5

这使它更易于重复使用,并且更容易测试。