I've taken up learning Haskell again, after a short hiatus and I am currently trying to get a better understanding of how recursion and lambda expressions work in Haskell.
In this: YouTube video, there is a function example that puzzles me far more than it probably should, in terms of how it actually works:
firstThat :: (a -> Bool) -> a -> [a] -> a
firstThat f = foldr (\x acc -> if f x then x else acc)
For the sake of clarity and since it wasn't immediately obvious to me, I'll give an example of applying this function to some arguments:
firstThat (>10) 2000 [10,20,30,40] --returns 20, but would return 2000, if none of the values in the list were greater than 10
Please correct me, if my assumptions are wrong.
It seems firstThat
takes three arguments:
- a function that takes one arguments and returns a Boolean value. Since the
>
operator is actually an infix function, the first argument in the example above seems the result of a partial application to the>
function – is this correct? - an unspecified value of the same type expected as the missing argument to the function provided as the first argument
- a list of values of the aforementioned type
But the actual function firstThat
seems to be defined differently from its type declaration, with just one argument. Since foldr
normally takes three arguments I gathered there is some kind of partial application happening. The lambda expression provided as an argument to foldr
seem to be missing its arguments too.
So, how exactly does this function work? I apologize if I am being too dense or fail to see the forest for the trees, but I just cannot wrap my head around it, which is frustrating.
Any helpful explanation or example(s) would be greatly appreciated.
Thanks!