【问题标题】:Variadic compose function?可变参数撰写功能?
【发布时间】:2012-03-11 16:39:25
【问题描述】:

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

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

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

【问题讨论】:

  • 你能解释一下“可变函数组合”是什么意思吗?也许添加一些例子。
  • 我在上次编辑中澄清了一点。除此之外,给定的两个例子有什么问题?
  • 哦,对不起。例子很好。对我来说,他们不进行类型检查并不明显。
  • 您可能需要查看Concatenative, Row-Polymorphic Programming in HaskellPlaying with Factor's Row Polymorphism in Haskell,因为行多态性对于组合所有类型的函数特别有用。
  • @is7s,FWIW,任何带有“可变参数”的东西都不太可能与其他语言配合得很好。它可以通过 typeclass hack 实现,而且很有趣,但我不建议将它用于“真实代码”。

标签: haskell variadic function-composition pointfree


【解决方案1】:

可以将其键入到与多态函数一起使用:

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

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 2016-10-22
    • 1970-01-01
    • 2022-10-04
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2021-04-13
    相关资源
    最近更新 更多