gpt4 book ai didi

haskell - 可变参数组合函数?

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

我正在尝试编写一个可变参数函数组合函数。这基本上就是 (.) ,只不过第二个参数函数是可变参数。这应该允许这样的表达式:

map even . zipWith (+)

或者只是

map even . zipWith

目前,如果我添加 IncoherentInstances 并且需要第一个参数函数的非多态实例,我所达到的效果就可以实现。

{-# LANGUAGE FlexibleInstances, OverlappingInstances, MultiParamTypeClasses, 
FunctionalDependencies, UndecidableInstances, KindSignatures #-}

class Comp a b c d | c -> d where
comp :: (a -> b) -> c -> d

instance Comp a b (a :: *) (b :: *) where
comp f g = f g

instance Comp c d b e => Comp c d (a -> b) (a -> e) where
comp f g = comp f . g

有什么想法吗?这可能吗?

最佳答案

可以对其进行类型破解以使用多态函数:

{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses,
IncoherentInstances, UndecidableInstances,
FunctionalDependencies, TypeFamilies,
NoMonomorphismRestriction #-}


class Comp a b c | a b -> c where
(...) :: a -> b -> c

instance (a ~ c, r ~ b) => Comp (a -> b) c r where
f ... g = f g

instance (Comp (a -> b) d r1, r ~ (c -> r1)) => Comp (a -> b) (c -> d) r where
f ... g = \c -> f ... g c

t1 = map even ... zipWith (+)
t2 = map even ... zipWith
t3 = (+1) ... foldr

但我怀疑你能否避免IncoherentInstances

关于haskell - 可变参数组合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656797/

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