本文介绍了可变组合函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个可变参数函数组合函数.这基本上是 (.)
,除了第二个参数函数是可变参数.这应该允许以下表达式:
I'm trying to write a variadic function composition function. Which is basically the (.)
except that the second argument function is variadic. This should allow expressions like:
map even . zipWith (+)
或者只是
map even . zipWith
目前,如果我添加 IncoherentInstances
并且需要第一个参数函数的非多态实例,我所达到的效果.
Currently what I've reached works if I add IncoherentInstances
and requires a non-polymorphic instance for the first argument function.
{-# 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
有什么想法吗?甚至有可能吗?
Any ideas? Is it even possible?
推荐答案
可以通过 type-hack 它来处理多态函数:
It is possible to type-hack it into working with polymorphic functions:
{-# 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
这篇关于可变组合函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!