Haskell - 类型类扩展

标签 haskell

我有一个关于类型类的问题。我有以下代码:

import Foreign.C.Types (CDouble, CFloat)

class Floating a => Trigonometry a where

    versin :: a -> a
    versin x = 1 - cos x

    vercos :: a -> a
    vercos x = 1 + cos x

    coversin :: a -> a
    coversin x = 1 - sin x

    covercos :: a -> a
    covercos x = 1 + sin x

    haversin :: a -> a
    haversin x = versin x * 0.5

    havercos :: a -> a
    havercos x = vercos x * 0.5

    hacoversin :: a -> a
    hacoversin x = coversin x * 0.5

    hacovercos :: a -> a
    hacovercos x = covercos x * 0.5

instance Trigonometry CDouble
instance Trigonometry CFloat
instance Trigonometry Double
instance Trigonometry Float

现在我的问题是:可以有无限数量的 Floating 实例,显然 Floating 的每个实例都可以是 Trigonometry 无需额外实现。有没有办法避免在底部显式声明实例并自动使所有 Floating 实例也成为 Trigonometry 实例?

干杯!

最佳答案

对于这种情况,可能根本不需要定义类型类,您可以将这些函数实现为具有 Floating 类型约束的顶级函数:

versin :: <strong>Floating a =></strong> a -> a
versin x = 1 - cos x

vercos :: <strong>Floating a =></strong> a -> a
vercos x = 1 + cos x

coversin :: <strong>Floating a =></strong> a -> a
coversin x = 1 - sin x

covercos :: <strong>Floating a =></strong> a -> a
covercos x = 1 + sin x

haversin :: <strong>Floating a =></strong> a -> a
haversin x = versin x * 0.5

havercos :: <strong>Floating a =></strong> a -> a
havercos x = vercos x * 0.5

hacoversin :: <strong>Floating a =></strong> a -> a
hacoversin x = coversin x * 0.5

hacovercos :: <strong>Floating a =></strong> a -> a
hacovercos x = covercos x * 0.5

如果你想为某个Floating 类型做一个特殊的实现,你确实可以使用类型类,但是如果你实现一个instance Floating a => Trigonometry a,你可能最终会得到 overlapping instances .

关于Haskell - 类型类扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70860896/

相关文章:

haskell - 如何修复构建 gtk2hs 包的 "Unacceptable result type in foreign declaration: CULong"错误?

haskell - 无限输入的非确定性

haskell - Functor/Applicative 可以绑定(bind)到一种特定的类型或结构吗?

list - 平面列表和自由单子(monad)

haskell - Bifunctor 实例定义上的类型签名不匹配

haskell - Yesod应用形式

haskell - 了解 Monad '>>=' 函数中的 forall 吗?

haskell - Haskell 中的库函数是如何实现的

haskell - 为 Haskell GADT 定义 Eq 实例

Haskell 从文件读取整数到列表