Haskell 用于左折叠操作的无点函数
我有一个从元组中提取第四个元素的函数,它恰好是一个整数:Haskell 用于左折叠操作的无点函数,haskell,fold,pointfree,Haskell,Fold,Pointfree,我有一个从元组中提取第四个元素的函数,它恰好是一个整数: fourth :: (a, b, c, Int) -> Int fourth (a, b, c, d) = d 我想求元组列表中所有第四个整数的和。我可以在右折叠操作中使用foldr,方法是将其与(+)组合成合适的foldr操作符: summerRight :: (a, b, c, Int) -> Int -> Int summerRight tuple n = fourth tuple + n summerLeft
fourth :: (a, b, c, Int) -> Int
fourth (a, b, c, d) = d
我想求元组列表中所有第四个整数的和。我可以在右折叠操作中使用foldr
,方法是将其与(+)
组合成合适的foldr
操作符:
summerRight :: (a, b, c, Int) -> Int -> Int
summerRight tuple n = fourth tuple + n
summerLeft :: Int -> (a, b, c, Int) -> Int
summerLeft n tuple = n + fourth tuple
整件事都可以写得毫无意义:
summerRight = (+) . fourth
现在,如果我想将总和表示为左折,我需要一个运算符:
summerRight :: (a, b, c, Int) -> Int -> Int
summerRight tuple n = fourth tuple + n
summerLeft :: Int -> (a, b, c, Int) -> Int
summerLeft n tuple = n + fourth tuple
我无法无点编写最后一个函数
是否可以编写summerLeft
pointfree
如果不是,是否有一些可能的推理将折叠权限与无点编程联系起来?您可以使用flip::(a->b->c)->b->a->c
:
fourth :: (a, b, c, Int) -> Int
fourth (a, b, c, d) = d
summerLeft :: Int -> (a, b, c, Int) -> Int
summerLeft = flip ((+) . fourth)
main :: IO ()
main = print $ summerLeft 1 (2, 3, 4, 5)
印刷品
6
下面是另一个解决方案:
summerLeft n tuple = n + fourth tuple
summerLeft n = (n +) . fourth
summerLeft = (. fourth) . (+)
嗯,它让我想起了画眉组合体Txy=yx。看起来是一种通用的方法。谢谢您。