【问题标题】:Haskell: function parse error at the beginningHaskell:开头的函数解析错误
【发布时间】:2019-10-13 13:50:12
【问题描述】:

我是 haskell 的初学者,正在尝试执行密码验证功能。

 validateCipher :: [Char] -> Bool
 validateCipher cipher =
       if length $ nub cipher == length cipher  
        then return True
        else return False

当我通过 ghci 运行它时,它只是告诉我:error: parse error on input ‘validateCipher’。 不知道出了什么问题,我应该添加 Eq 还是任何东西(我也不太确定它有什么作用)?

【问题讨论】:

  • 删除return。在 Haskell 中没有 return 关键字,只有一个 return 函数。此外,$ 会将其解析为 `length (nub cipher == length cipher),因此您应该使用括号。

标签: haskell


【解决方案1】:

这里有两个错误:

  1. 你使用return。在 Haskell 中有 no return keyword,有一个 return :: Monad a => a -> m a 函数,但工作方式不同;和
  2. $ 导致length $ nub cipher == length cipher 被解析为length (nub cipher == length cipher),这不满足类型约束,因为nub cipher 返回一个[Char],而length cipher 将返回一个@ 987654332@.

这里首先不需要return TrueTrue,因为我们可以只返回我们检查的条件的结果。我们还可以用括号写出正确的表达式:

validateCipher :: [Char] -> Bool
validateCipher cipher = length (nub cipher) == length cipher

【讨论】:

  • Q1 原因是我搜索并发现有人在 Haskell 中使用 return True .....非常感谢您提供更可靠的答案。
  • @GTTT:非常适合单元计算,例如IOMaybe 等。有时确实可以使用return。但不适用于非单子的,比如这里的。
  • Q2 我没有完全理解 $ 运算符,但现在因为你的解释,我会更有信心!非常感谢
  • @GTTT:($)是一个优先级很低的运算符(haskell.org/onlinereport/decls.html),它基本上是用来对左边的部分和右边的部分进行分组,然后做一个功能应用。所以... $ ...,几乎总是等价于(...) (...)(但没有括号)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多