I'd like to write a tail-recursive foldr in f#, to take advantage of the tail-recursion optimization and learn more about functional programming.
I've written a tail-recursive foldl, and a foldr that isn't tail-recursive. I thought I could get a tail-recursive foldr by reversing the list fed to the function, then calling my tail recursive foldl on it, but this doesn't work because of the different order the function is supposed to be applied to.
let rec tail_recurse_foldl(list: List<'a>, func:('b -> 'a -> 'b), acc: 'b) =
match list with
| [] -> acc
| [x] -> func acc x
| x :: xs -> tail_recurse_foldl(xs, func, func acc x)
and non tail-recursive foldr
let rec foldr(list: List<'a>, func:('a -> 'b -> 'b), acc: 'b) =
match list with
| [] -> acc
| [x] -> func x acc
| x::xs -> func x (foldr(xs, func, acc))
foldlandfoldrare older than Haskell. In Lisp, especially Scheme, there has been some flipping where R6RS followed the accumulator as last argument forfoldrbut both earlier and older version has the same signature, though I think this is because these are not curried lazy languages like Haskell. - Sylwester