gpt4 book ai didi

haskell - 在 Haskell 中提升类实例

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

有没有办法在 Haskell 中轻松“提升”一个类实例?

我经常需要为某些类创建例如 Num 实例,这些类只是通过类型构造函数“提升” Num 结构,如下所示:

data SomeType a = SomeCons a

instance (Num a)=>Num SomeCons a where
(SomeCons x) + (SomeCons y) = SomeCons (x+y)
negate (SomeCons x) = SomeCons (negate x)
-- similarly for other functions.

有没有办法避免这个样板并自动“提升”这个 Num 结构?当我尝试学习存在时,我通常也必须对 Show 和其他类执行此操作,而编译器不允许我使用 deriving(Show) .

最佳答案

广义的新类型派生扩展是您想要的:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Main where

newtype SomeType a = SomeCons a deriving (Num, Show, Eq)

main = do
let a = SomeCons 2
b = SomeCons 3
print $ a + b

输出:
*Main> main
SomeCons 5

关于haskell - 在 Haskell 中提升类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1816817/

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