首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单输入函数Haskell

简单输入函数Haskell
EN

Stack Overflow用户
提问于 2017-12-22 19:21:11
回答 2查看 556关注 0票数 1

我想编写一个简单的函数,从控制台读取字符串并将其解析为自定义数据类型。

我的尝试:

代码语言:javascript
复制
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时遇到的错误。

代码语言:javascript
复制
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 }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-12-22 19:40:41

您有两个类型错误。第二个更容易理解:

代码语言:javascript
复制
getFormula::IO Custom

getFormula被声明为具有IO Custom类型。

代码语言:javascript
复制
    return read toParse::Custom

..。但是在这里,您可以断言最后一个表达式的类型是CustomIO CustomCustom不一样,所以编译器会抱怨。

顺便说一句,你的间隔有点奇怪。为什么::对左边和右边的标识符右卡住了?

代码语言:javascript
复制
    return read toParse :: Custom

看起来不那么拥挤,也不那么误导::: Custom部分适用于左边的整个表达式,而不仅仅是一个变量。

第一个错误有点混乱,但它包含一个重要提示:The function ‘return’ is applied to two arguments

return只使用一个论点:

代码语言:javascript
复制
return read toParse

应该是

代码语言:javascript
复制
return (read toParse)

为了也修复类型注释,您可以使用以下之一:

  • 有点笨重: 返回(阅读toParse) ::IO自定义
  • 稍微整洁一点(不需要指定IO): 返回(阅读toParse ::定制)
  • 最简单的解决办法: 返回(读toParse) 您根本不需要在这里显式指定类型。编译器已经知道您正在寻找Custom,因为getFormula :: IO Custom声明。
票数 2
EN

Stack Overflow用户

发布于 2017-12-22 19:39:35

return函数有一个参数,但是给它两个--第一个是read,第二个是toParse

使用括号指定应用程序顺序:

代码语言:javascript
复制
return (read toParse :: Custom)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47946382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档