如何在 Haskell 中使用 fromInteger 而不使用隐式前奏?

发布于 2024-09-28 17:47:37 字数 828 浏览 1 评论 0原文

以下程序在 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) 添加实例声明
在模式中:1
fromInteger'的定义中:fromInteger 1 = one

我该如何修复它,以便 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 literal 1' at fromInteger.hs:17:16
Possible fix: add an instance declaration for (Monoid Integer)
In the pattern: 1
In the definition of
fromInteger': fromInteger 1 = one

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-10-05 17:47:37

问题是(使用 NoImlitPrelude)您只能对范围内有 fromInteger 函数的类型使用整数文字。

因此,在您的代码中,您只能使用整数文字来表示 Monoid 的实例,并且因为在您的代码中,Integer 不是 Monoid 的实例,您不能使用文字 1 来表示整数 1。

要解决此问题,您可以创建另一个模块来导入 prelude 并定义 integerOne :: Integer = 1

然后,您可以将 fromInteger 函数定义为:

fromInteger x | x == integerOne = one

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 of Monoid, you can not use the literal 1 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:

fromInteger x | x == integerOne = one
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文