带有元组参数的Haskell中的函数组合 [英] Function composition in Haskell with tuple arguments
问题描述
有时我有两种形式的函数:
Sometimes I have two functions of the form:
f :: a -> (b1,b2)
h :: b1 -> b2 -> c
并且我需要构图g。我通过将h改为h来解决这个问题:
and I need the composition g. I solve this by changing h to h':
h' :: (b1,b2) -> c
您可以告诉我(如果可能的话)函数m,以便:
Can you please show me (if possible) a function m, so that:
(h . m . f) == (h' . f)
或者另一种处理这种情况的方式。感谢。
Or another way to deal with such situations. Thanks.
推荐答案
你正在做的是采用一个在 curried 参数, h
,并将其应用于元组的结果 f
。这个过程将两个参数的函数转换为一个带有一个元组参数的函数,称为 uncurrying 。我们从 Data.Tuple < a>:
What you're looking to do is to take a function that operates on curried arguments, h
, and apply it to the result of f
, which is a tuple. This process, turning a function of two arguments into a function that takes one argument that is a tuple, is called uncurrying. We have, from Data.Tuple:
curry :: ((a, b) -> c) -> a -> b -> c
-- curry converts an uncurried function to a curried function.
uncurry :: (a -> b -> c) -> (a, b) -> c
-- uncurry converts a curried function to a function on pairs.
现在我们可以写出:
So now we can write:
f :: a -> (b,c)
f = undefined
h :: b -> c -> d
h = undefined
k :: a -> d
k = uncurry h . f
另一个难以想象的方法是通过应用仿函数b
$ b
Another tricky way to think of this is via an applicative functor,
k = (h <$> fst <*> snd) . f
来自Conor McBride的想法,他会把它写成: f fst snd |)。 f
我想。
Idea from Conor McBride, who'd write it as: (|f fst snd|) . f
I think.
这篇关于带有元组参数的Haskell中的函数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!