【发布时间】:2015-11-02 17:06:50
【问题描述】:
我无法让以下内容在 GHCi 中工作。这是一个在网上弹出几个地方的简短示例。
import Data.Maybe
elseZero :: (Num a) => Maybe a -> a
elseZero n = fromMaybe 0 n
我的理解是,当我将它加载到 GHCi 中然后使用 elseZero 运行时,它应该返回 0,因为没有给出任何参数。
但我收到错误:
Non type-variable argument in the constraint: Num (Maybe a)
(Use FlexibleContexts to permit this)
When checking that `it' has the inferred type
it :: forall a. (Num a, Num (Maybe a)) => a
Haskell 的 Monadic 的所有部分都是新的。感谢您的帮助!
【问题讨论】:
-
您的问题源于对
fromMaybe的误解以及对elseZero的类型签名的混淆:elseZero是一个需要一个参数的函数(Maybe a)。如果您尝试评估它而不提供Maybe a类型的值,GHCi 会抱怨。elseZero Nothing返回0,因为无法从Nothing中提取任何值。 -
Maybe a不是可选参数,您必须提供Maybe a类型的值,例如fromMaybe Nothing或fromMaybe (Just 3). -
谢谢@Jubobs。查看 Just (a -> Maybe a) 和 Nothing 数据构造函数的类型非常有帮助。我希望通过使可选函数参数采用默认值来使用 Maybe 来清理一些代码。我现在看到这需要使用 Just 或辅助函数。
-
@todkwxrtvwmzonunswam 你可能会喜欢 Brent Yorgey 在incremental ad-hoc parameter abstraction 上的帖子。