gpt4 book ai didi

具有约束的 Haskell 实例

转载 作者:行者123 更新时间:2023-12-02 01:32:02 25 4
gpt4 key购买 nike

我正在尝试为带符号的数字类型创建一个类型类。这是我的代码:

{-# LANGUAGE TypeFamilies, FlexibleContexts, UndecidableInstances #-}

data Sign = Negative | Zero | Positive
deriving (Eq, Ord, Read, Show)

class Signed a where
sign :: a -> Sign

instance Signed Integer where
sign = undefined

这可以编译,但我想修改此代码以适用于任何 Integral a

instance (Integral a) => Signed a where
sign = undefined

编译失败。

我检查过 Haskell type family instance with type constraints ,但这似乎是在解决与我不同的问题。我不认为我的代码中存在语法错误。

最佳答案

尝试编译您的代码会产生以下错误消息:

sign.hs:9:26:
Illegal instance declaration for ‘Signed a’
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use FlexibleInstances if you want to disable this.)
In the instance declaration for ‘Signed a’
Failed, modules loaded: none.

正如编译器指出的那样,您需要打开 FlexibleInstances 以及 UndecidableInstances。 GHC 的错误消息通常非常具体,尤其是当您忘记打开语言扩展时。以下立即编译:

{-# LANGUAGE UndecidableInstances, FlexibleInstances #-}

data Sign = Negative | Zero | Positive
deriving (Eq, Ord, Read, Show)

class Signed a where
sign :: a -> Sign

instance (Integral a) => Signed a where
sign = undefined

但是,我认为 Signed 类在这个例子中可能是个错误。定义一个(非重载的)顶级函数要简单得多,不需要 UndecidableInstances(需要它通常是一种设计味道),并且更能表达意义 您的代码:“您可以获得符号的东西”正是实数。

sign :: Real a => a -> Sign
sign x
| x == 0 = Zero
| x < 0 = Negative
| otherwise = Positive

关于具有约束的 Haskell 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com