I'm struggling with mapping non trivial function to be tail recursive.
take even the simple rosetree
type Tree<'a> =
| Leaf of 'a
| Branch of List<Tree<'a>>
with map
let rec map : ('a -> 'b) -> Tree<'a> -> Tree<'b> =
fun f ->
function
| Leaf a ->
f a
|> Leaf
| Branch xs ->
xs
|> List.map (map f)
|> Branch
(let alone bind)
making this tail recursive seems quite painful, I've looked at examples in things like FSharpx, but they arent tail recursive. I have found this
https://www.gresearch.co.uk/article/advanced-recursion-techniques-in-f/
but the leap from the final example based on continuities seems quite bespoke to their example (of max), I can't seem to get my head around it.
is there an example implementation of this pretty canonical example somewhere?
so the simple bit would be something like this
let map2 : ('a -> 'b) -> Tree<'a> -> Tree<'b> =
fun f ta ->
let rec innerMap : Tree<'a> -> (Tree<'b> -> Tree<'b>) -> Tree<'b> =
fun ta cont ->
match ta with
| Leaf a ->
f a |> Leaf |> cont
innerMap ta id
but I'm missing the hard bit with branch