如何在 Haskell 中使用 fromInteger 而不使用隐式前奏?
以下程序在 ghci 中产生错误:
{-# LANGUAGE NoImplicitPrelude #-}
import Prelude (Integer, Bool)
import qualified Prelude
class Discrete a where
(==) :: a -> a -> Bool
instance Discrete Integer where
(==) = (Prelude.==)
class Monoid a where
one :: a
(*) :: a -> a -> a
fromInteger :: Integer -> a
fromInteger 1 = one
即:
fromInteger.hs:17:16:
没有(Monoid Integer)实例
源自 fromInteger.hs:17:16
处的文字1' 可能的修复:为 (Monoid Integer) 添加实例声明
fromInteger'的定义中:fromInteger 1 = one
在模式中:1
我该如何修复它,以便 1 可以转换为 Monoids 的值 one
?所有其他整数在应用于 (Monoid a) => 时可能(或应该)产生
。Prelude.undefined
来自整数
请注意,我是 Haskell 的相反专家,所以如果答案很明显,请原谅我。
The following program yields an error in ghci:
{-# LANGUAGE NoImplicitPrelude #-}
import Prelude (Integer, Bool)
import qualified Prelude
class Discrete a where
(==) :: a -> a -> Bool
instance Discrete Integer where
(==) = (Prelude.==)
class Monoid a where
one :: a
(*) :: a -> a -> a
fromInteger :: Integer -> a
fromInteger 1 = one
Namely:
fromInteger.hs:17:16:
No instance for (Monoid Integer)
arising from the literal1' at fromInteger.hs:17:16
fromInteger': fromInteger 1 = one
Possible fix: add an instance declaration for (Monoid Integer)
In the pattern: 1
In the definition of
How can I fix it so that 1 can be converted to the value one
for Monoids? All other integers may (or should) yield Prelude.undefined
when being applied to (Monoid a) => fromInteger
.
Please be aware that I am a the opposite of an expert to Haskell so please forgive me in case the answer is obvious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是(使用 NoImlitPrelude)您只能对范围内有
fromInteger
函数的类型使用整数文字。因此,在您的代码中,您只能使用整数文字来表示
Monoid
的实例,并且因为在您的代码中,Integer
不是Monoid
的实例,您不能使用文字1
来表示整数 1。要解决此问题,您可以创建另一个模块来导入 prelude 并定义
integerOne :: Integer = 1
。然后,您可以将
fromInteger
函数定义为:The problem is that (with NoImplitPrelude) you can only use integer literals for types for which there is a
fromInteger
function in scope.So in your code you can only use integer literals to represent instances of
Monoid
and since in your code,Integer
is not an instance ofMonoid
, you can not use the literal1
to represent the Integer 1.To fix this you could create another module which does import the prelude and define
integerOne :: Integer = 1
.You could then define your
fromInteger
function as: