【发布时间】:2017-12-22 19:21:11
【问题描述】:
我想编写一个简单的函数,从控制台读取字符串并将其解析为自定义数据类型。
我的尝试:
data Custom = A | B Int | C String deriving Read
getFormula::IO Custom
getFormula = do
putStrLn("Introduce una formula: ")
toParse <- getLine
return read toParse::Custom
但这不起作用,我不知道如何解释产生的编译错误。我该如何解决?我对 IO 函数的工作原理有什么误解?
编辑:这是我尝试将文件加载到 GCHI 时遇到的错误
test.hs:7:5:
Couldn't match type ‘String -> a0’ with ‘Custom’
Expected type: String -> Custom
Actual type: String -> String -> a0
The function ‘return’ is applied to two arguments,
but its type ‘(String -> a0) -> String -> String -> a0’
has only three
In a stmt of a 'do' block: return read toParse :: Custom
In the expression:
do { putStrLn ("Introduce una formula: ");
toParse <- getLine;
return read toParse :: Custom }
test.hs:7:5:
Couldn't match expected type ‘IO Custom’ with actual type ‘Custom’
In a stmt of a 'do' block: return read toParse :: Custom
In the expression:
do { putStrLn ("Introduce una formula: ");
toParse <- getLine;
return read toParse :: Custom }
In an equation for ‘getFormula’:
getFormula
= do { putStrLn ("Introduce una formula: ");
toParse <- getLine;
return read toParse :: Custom }
【问题讨论】:
-
你可以直接使用
readLn来代替getLine和read。