[英]Reading lines and reversing the text with Haskell
我的程序應執行以下操作:
但這是行不通的,作為Haskell新手,我無法理解錯誤。
這是我的代碼:
main = do
content <- readFile "test.txt"
let linesList = lines content
reverseLines
reverseWords :: String -> String
reverseWords = unwords . map reverse . words
reverseLines :: [String] -> IO ()
reverseLines inputList = do
if null inputList
then return ()
else do
line <- inputList!!0
if null line
then return ()
else do
putStrLn $ reverseWords line
reverseLines . tail inputList
我的錯誤:
readlines.hs:4:9:
Couldn't match expected type `IO b0'
with actual type `[String] -> IO ()'
In a stmt of a 'do' block: reverseLines
In the expression:
do { content <- readFile "test.txt";
let linesList = lines content;
reverseLines }
In an equation for `main':
main
= do { content <- readFile "test.txt";
let linesList = ...;
reverseLines }
readlines.hs:14:25:
Couldn't match type `[Char]' with `IO [Char]'
Expected type: [IO [Char]]
Actual type: [String]
In the first argument of `(!!)', namely `inputList'
In a stmt of a 'do' block: line <- inputList !! 0
In the expression:
do { line <- inputList !! 0;
if null line then
return ()
else
do { putStrLn $ reverseWords line;
.... } }
readlines.hs:19:33:
Couldn't match expected type `IO ()' with actual type `a0 -> IO ()'
In a stmt of a 'do' block: reverseLines . tail inputList
In the expression:
do { putStrLn $ reverseWords line;
reverseLines . tail inputList }
In a stmt of a 'do' block:
if null line then
return ()
else
do { putStrLn $ reverseWords line;
reverseLines . tail inputList }
readlines.hs:19:48:
Couldn't match expected type `a0 -> [String]'
with actual type `[String]'
In the return type of a call of `tail'
Probable cause: `tail' is applied to too many arguments
In the second argument of `(.)', namely `tail inputList'
In a stmt of a 'do' block: reverseLines . tail inputList
首先,您的main
函數中的最后一行是[String]-> IO()類型,並且您需要將其作為IO(),因此實際上需要向其傳遞字符串列表。 這是您要執行的操作的一種方法:
main :: IO ()
main = do
content <- readFile "test.txt"
let linesList = lines content
reverseLines linesList
reverseWords :: String -> String
reverseWords = unwords . map reverse . words
reverseLines :: [String] -> IO ()
reverseLines = mapM_ (putStrLn . reverseWords)
這是類似於您要在版本中執行的遞歸版本
reverseLines2 :: [String] -> IO ()
reverseLines2 [] = return ()
reverseLines2 (x:xs) = do
putStrLn (reverseWords x)
reverseLines2 xs
我還通過最少的更改修復了您的版本,但請記住,這實際上並不是Haskell的處理方式。 使用我上面提供的選項之一。
main = do
content <- readFile "test.txt"
let linesList = lines content
reverseLines linesList
reverseWords :: String -> String
reverseWords = unwords . map reverse . words
reverseLines :: [String] -> IO ()
reverseLines inputList = do
if null inputList
then return ()
else do
let line = head inputList
if null line
then return ()
else do
putStrLn $ reverseWords line
reverseLines $ tail inputList
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.