我是一个haskell初学者。我的代码:
module Main (main) where
import System.IO
--Type for identifying Students.
data Student = Student {
name :: String,
regnum :: Integer
} deriving (Show, Read)
getData :: IO (String)
getData = do
putStr "\tEnter the student's name: "
name <- getLine
putStr "\tEnter the registration number: "
regstr <- getLine
let regno = (read regstr) :: Integer
return (show ( Student name regno ))
addData :: String -> IO (Bool)
addData filename = do
fileData <- getData
appendFile filename fileData
return True
printData :: String -> IO (Bool)
printData filename = do
fileData <- readFile filename
putStrLn fileData
return True
resetFile :: String -> IO (Bool)
resetFile filename = writeFile filename "" >> return True
action :: Char -> String -> IO (Bool)
action option filename =
if option == '1'
then addData filename
else if option == '2'
then printData filename
else if option == '3'
then resetFile filename
else return False
main = do
putStr "What do you want to do?\n\t1) Add a new record to a file.\n\t2) Read a record from a file.\n\t3) Reset the file.\n>> "
option <- getChar
action option "records.txt"
我得到的输出是:
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
>> 1
Enter the student's name: Enter the registration number:
因此,我无法为学生的姓名提供输入。我在ghci上运行代码。当我试图查看它如何作为可执行文件运行时,它给出了更奇怪的输出。
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
(注意它不打印“>>”)。只有在我按两次 Enter 后,它才会打印“>>”。我不明白这里发生了什么。非常欢迎对我的代码进行其他改进。
编辑:: 通过使用 getLine 而不是 getChar ,该程序可以在 ghci 上运行(感谢 Daniel Fischer)。但是编译的时候还是不行。新的输出是:
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
1 (Typed my me)
Tom (Typed my me)
234 (Typed my me)
>> Enter the student's name: Enter the registration number:
在重新运行以读取文件时:
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
2 (Typed my me)
>> Student {name = "Tom", regnum = 234}
为什么putStr
输入后会打印“>>”和getData?