gpt4 book ai didi

haskell - 多态约束

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

我有一些做作的类型:

{-# LANGUAGE DeriveFunctor #-}

data T a = T a deriving (Functor)

...该类型是某些人为类的实例:

class C t where
toInt :: t -> Int

instance C (T a) where
toInt _ = 0

如何在函数约束中表达 T a 是所有 a 的某个类的实例?

例如,考虑以下函数:

f t = toInt $ fmap Left t

直观上,我希望上述函数能够工作,因为 toInt 适用于所有 aT a,但我无法用以下方式表达这一点:方式。这不起作用:

f :: (Functor t, C (t a)) => t a -> Int

...因为当我们应用fmap时,类型已变为Either a b。我无法使用以下方法修复此问题:

f :: (Functor t, C (t (Either a b))) => t a -> Int

...因为b不代表通用量化变量。我也不能说:

f :: (Functor t, C (t x)) => t a -> Int

...或使用 forall x 表明该约束对所有 x 均有效。

所以我的问题是是否有一种方法可以说约束对于其某些类型变量是多态的。

最佳答案

使用constraints封装:

{-# LANGUAGE FlexibleContexts, ConstraintKinds, DeriveFunctor, TypeOperators #-}

import Data.Constraint
import Data.Constraint.Forall

data T a = T a deriving (Functor)

class C t where
toInt :: t -> Int

instance C (T a) where
toInt _ = 0

f :: ForallF C T => T a -> Int
f t = (toInt $ fmap Left t) \\ (instF :: ForallF C T :- C (T (Either a b)))

关于haskell - 多态约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12718268/

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