3 ms·
In functional languages, recursive data structures are often most naturally walked with recursive functions. Languages like Haskell and ML take this to its nat
by retrac 4y ago
In functional languages, recursive data structures are often most naturally walked with recursive functions. Languages like Haskell and ML take this to its natural conclusion and use it systematically. For example, a linked list. Here's how the Haskell "last" function, to get the last item in a linked list, is implemented in the standard library:
last [x] = x
last (_:xs) = last xs
last [] = errorEmptyList "last"
If given a list with a single item, return that item. If given a list with two or more items, call itself with the list minus its head. If given an empty list, throw an error.
- nu11ptr 4y agoThis is the scenario I am used to using where "last" is called in tail position calling itself, but I see from the other answers there are definitely valid use cases for non-same function recursion as well