Search code examples
haskellfoldpointfree

Pointfree function for fold left operation


I have this function that extracts the fourth element, which happens to be an integer, out of a tuple:

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

I want to sum all the fourth integers of a list of tuples. I can use fourth inside a fold right operation by composing it with (+) into a suitable foldr operator:

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

the whole thing can be written pointfree:

summerRight = (+) . fourth

Now, if I want to express the sum as a fold left, I need an operator:

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

I cannot manage to write this last function pointfree.

Is it possible to write summerLeft pointfree?

If it's not, is there some possible reasoning that relates fold right with pointfree programming?


Solution

  • You can use flip :: (a -> b -> c) -> b -> a -> c for this:

    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)
    

    prints

    6