14

我正在尝试编写一个可变参数函数组合函数。这基本上是(.)除了第二个参数函数是可变的。这应该允许如下表达式:

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

有任何想法吗?甚至可能吗?

4

1 回答 1

10

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

{-# 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

于 2012-03-12T10:33:47.013 回答