Jog*_*usa 13 haskell tuples currying function-composition
有时我有两种形式的功能:
f :: a -> (b1,b2)
h :: b1 -> b2 -> c
Run Code Online (Sandbox Code Playgroud)
我需要组合物g.我通过将h改为h'来解决这个问题:
h' :: (b1,b2) -> c
Run Code Online (Sandbox Code Playgroud)
你能告诉我(如果可能的话)一个函数m,这样:
(h . m . f) == (h' . f)
Run Code Online (Sandbox Code Playgroud)
或者另一种处理这种情况的方法.谢谢.
Don*_*art 16
你要做的是采用一个运行curried参数的函数h,并将它应用于结果f,这是一个元组.这个过程将两个参数的函数转换为一个函数,该函数接受一个作为元组的参数,称为uncurrying.我们有来自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.
Run Code Online (Sandbox Code Playgroud)
所以现在我们可以写:
f :: a -> (b,c)
f = undefined
h :: b -> c -> d
h = undefined
k :: a -> d
k = uncurry h . f
Run Code Online (Sandbox Code Playgroud)
考虑这个问题的另一个棘手的方法是通过一个应用函子,
k = (h <$> fst <*> snd) . f
Run Code Online (Sandbox Code Playgroud)
来自Conor McBride的想法,他把它写成:(|f fst snd|) . f我想.