[英]Haskell Parsing Error on 'let'
嘿,我在解析錯誤時遇到了問題,對此我很陌生。 關於Haskell的空白規則,我發現不多。 如果您能指出正確的方向,將不勝感激。
碼:
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))
您的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
這使得它更可重用且更容易測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.