Not a bad start! The only thing to remember is that pure function application should use let
instead of the binding <-
.
import System.IO
import Control.Monad
main = do
let list = []
handle <- openFile "test.txt" ReadMode
contents <- hGetContents handle
let singlewords = words contents
list = f singlewords
print list
hClose handle
f :: [String] -> [Int]
f = map read
This is the minimal change needed to get the thing to compile and run. Stylistically, I have a few comments:
- Binding
list
twice looks a bit shady. Note that this isn't mutating the value list
-- it's instead shadowing the old definition.
- Inline pure functions a lot more!
- When possible, using
readFile
is preferable to manually opening, reading, and closing a file.
Implementing these changes gives something like this:
main = do
contents <- readFile "test.txt"
print . map readInt . words $ contents
-- alternately, main = print . map readInt . words =<< readFile "test.txt"
readInt :: String -> Int
readInt = read
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…