我想编写一个简单的函数,从控制台读取字符串并将其解析为自定义数据类型。
我的尝试:
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 }发布于 2017-12-22 19:40:41
您有两个类型错误。第二个更容易理解:
getFormula::IO CustomgetFormula被声明为具有IO Custom类型。
return read toParse::Custom..。但是在这里,您可以断言最后一个表达式的类型是Custom。IO Custom和Custom不一样,所以编译器会抱怨。
顺便说一句,你的间隔有点奇怪。为什么::对左边和右边的标识符右卡住了?
return read toParse :: Custom看起来不那么拥挤,也不那么误导::: Custom部分适用于左边的整个表达式,而不仅仅是一个变量。
第一个错误有点混乱,但它包含一个重要提示:The function ‘return’ is applied to two arguments。
return只使用一个论点:
return read toParse应该是
return (read toParse)为了也修复类型注释,您可以使用以下之一:
IO):
返回(阅读toParse ::定制)Custom,因为getFormula :: IO Custom声明。发布于 2017-12-22 19:39:35
return函数有一个参数,但是给它两个--第一个是read,第二个是toParse。
使用括号指定应用程序顺序:
return (read toParse :: Custom)https://stackoverflow.com/questions/47946382
复制相似问题