简单的输入函数Haskell
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的输入函数Haskell相关的知识,希望对你有一定的参考价值。
我想编写一个简单的函数,从控制台读取一个字符串并将其解析为自定义数据类型。
我的尝试:
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 }
答案
您有两种类型错误。第二个更容易理解:
getFormula::IO Custom
getFormula
被宣布为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)
为了修复类型注释,您可以使用以下方法之一:
- 有点笨重:
return (read toParse) :: IO Custom
- 稍微整洁(不需要指定
IO
):return (read toParse :: Custom)
- 最简单的解决方案
return (read toParse)
您根本不需要在此处明确指定类型。由于Custom
声明,编译器已经知道你正在寻找getFormula :: IO Custom
。
另一答案
return
函数有一个参数,但你给它两个 - 第一个是read
,第二个是toParse
。
使用括号指定应用程序顺序:
return (read toParse :: Custom)
以上是关于简单的输入函数Haskell的主要内容,如果未能解决你的问题,请参考以下文章