2015-11-28 49 views
2

我有這樣的功能,提取的第四個元素,這恰好是一個整數,出數組:Pointfree功能倍左操作

fourth :: (a, b, c, Int) -> Int 
fourth (a, b, c, d) = d 

我要總結的列表的所有第四整數元組。我可以通過組合其與(+)使用fourth摺疊正確的操作中到合適的foldr操作:

summerRight :: (a, b, c, Int) -> Int -> Int 
summerRight tuple n = fourth tuple + n 

整個事情可以寫pointfree:現在

summerRight = (+) . fourth 

,如果我想表達的總結爲一個摺疊,我需要一個運算符:

summerLeft :: Int -> (a, b, c, Int) -> Int 
summerLeft n tuple = n + fourth tuple 

我無法設法寫這最後一個函數pointfree。

是否可以寫summerLeft pointfree?

如果不是,是否有一些可能的推理將摺疊權與無點編程相關聯?

回答

3

您可以使用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 
+0

Mmmh,它讓我想起了畫眉組合子TXY = YX的。看起來像一個普遍的方法。謝謝。 –

1

這裏是另一種解決方案:

summerLeft n tuple = n + fourth tuple 
summerLeft n = (n +) . fourth 
summerLeft = (. fourth) . (+)