gpt4 book ai didi

haskell - 将 Data.Constraint.Forall 与等式约束一起使用

转载 作者:行者123 更新时间:2023-12-02 15:34:23 26 4
gpt4 key购买 nike

假设我有一个这样的函数:

{-# LANGUAGE ScopedTypeVariables #-}

class C a where

foo :: forall f a b. (C (f a), C (f b)) => f a -> f b
foo = _

现在,如果我想将 ab 的范围移动到 foo 类型中类型类约束的右侧(假设,因为我想使用 foo 来实现需要在 ab 中实现多态的类型类方法),它可以完成使用 Data.Constraint.Forall 进行一些跑腿工作:

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds, TypeOperators #-}
import Data.Constraint
import Data.Constraint.Forall

foo' :: forall f. (ForallF C f) => forall a b. f a -> f b
foo' = helper
where
helper :: forall a b. f a -> f b
helper = case (instF :: ForallF C f :- C (f a)) of
Sub Dict -> case (instF :: ForallF C f :- C (f b)) of
Sub Dict -> foo

现在,我的问题是,假设我将函数更改为涉及类型相等的函数:

{-# LANGUAGE TypeFamilies, ScopedTypeVariables #-}

type family F a :: * -> *

bar :: forall f g a b. (F (f a) ~ g a, F (f b) ~ g b) => f a -> f b
bar = _

有没有办法使上述技术适应这一点?

这是我尝试过的:

{-# LANGUAGE TypeFamilies, ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds, TypeOperators #-}
import Data.Constraint
import Data.Constraint.Forall

type F'Eq f g x = F (f x) ~ g x

bar' :: forall f g. (Forall (F'Eq f g)) => forall a b. f a -> f b
bar' = helper
where
helper :: forall a b. f a -> f b
helper = case (inst :: Forall (F'Eq f g) :- F'Eq f g a) of
Sub Dict -> case (inst :: Forall (F'Eq f g) :- F'Eq f g b) of
Sub Dict -> bar

但是(毫不奇怪)由于不饱和类型同义词而失败:

Type synonym ‘F'Eq’ should have 3 arguments, but has been given 2

In an expression type signature: Forall (F'Eq f g) :- F'Eq f g a

In the expression: (inst :: Forall (F'Eq f g) :- F'Eq f g a)

最佳答案

您可以使用一个类:

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}

class (F (f x) ~ g x) => F'Eq f g x
instance (F (f x) ~ g x) => F'Eq f g x

bar' :: forall f g. (Forall (F'Eq f g)) => forall a b. f a -> f b
bar' = helper
where
helper :: forall a b. f a -> f b
helper = case (inst :: Forall (F'Eq f g) :- F'Eq f g a) of
Sub Dict -> case (inst :: Forall (F'Eq f g) :- F'Eq f g b) of
Sub Dict -> bar

关于haskell - 将 Data.Constraint.Forall 与等式约束一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28066534/

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