|
After the first 2, the rest are based on common and very useful abstractions. You could translate those to an OO language quite easily too, though with a lot more code. For example, what foldl does, from my understanding, is to recursively apply a function to both a starting value and the first element of a list, and then the same thing again, where the result from the last call becomes the starting value and the rest of the list becomes the list we're working on, up until the list is empty. Not sure if I've explained this well but I've not been into this long. If you see the second function, that's what it's doing, except it's working just with numbers and not a list. Since foldl works on lists, you need an enumerator, which in this case is just 1 through to n. The sixth example is great here. Product could easily be an abstraction on something quite similar to three, which itself could very well be an abstraction quite similar to two (using lists, functions to deal with lists and a given function). Please correct me if I'm wrong at any point here. I'm looking to improve these skills quite a lot so it'd be very, very welcome. |
The [1..3] is just sugar for 1:2:3:[]
Product is not actually an abstraction as it's restricted to work on number types.
And no foldl is not an abstraction of (2) because foldl is tail recursive while (2) is not. foldr is not tail recursive however and combined with haskell's laziness can make short work of infinite lists. But you are right in that any tail recursive function on a list can be rewritten using foldl. What is particular to haskell vs a strict language like say F# is that foldl can still pop a stack due to haskell's laziness. You want foldl' as it will force the initial argument. Fold is also a fundamental operation on any algebraic data structure such as trees , lists, and natural numbers. You can write filter, map, filtermap etc in terms of it for example. There is so much to say about fold - they are like the cupboard which leads to narnia.. but I will stop now so as not to turn this into an infodump.