2012-03-11 70 views
13

我想寫一個可變參數函數組合函數。這基本上是(.),只是第二個參數函數是可變參數。這應該允許這樣的表達式:Variadic撰寫功能?

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 

任何想法?它甚至有可能嗎?

+1

你能解釋一下多一點你是什麼意思「可變參數函數組成的意思「?也許增加一些例子。 – 2012-03-11 16:44:01

+0

我在最後的編輯中稍微澄清了一點。除此之外,這兩個例子有什麼不對? – is7s 2012-03-11 16:47:46

+0

哦,對不起。例子很好。對我來說,他們不會檢查是不明顯的。 – 2012-03-11 16:53:25

回答

9

它可以將其類型攻入具有多態函數工作:

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