Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Ivo's answered so I'll just say the main trick to turning a function tail recursive is to have the function lug its state around. So always look to see if you can rewrite your function so it passes the current value explicitly to the next iteration. Non tail recursion is like winding a spring and then having it unwind, a jack in a box. Tail recursion is like a snowball rolling down a hill. You should always try to make a recursive function tail recursive if you can.

As for fold it's a bit involved and has a lot of scary sounding jargon on the way to understanding it. You can write a fold for a tree and then code depth first search in a couple lines. Folds follow some basic properties that allow for program derivation. I rarely use those but it does inform my programming. It's kind of like how knowing Lisp informs your python. There is also an opposite or dual to fold called unfold. You can write many algorithms efficiently just using fold and unfold and a couple techniques to prune inefficiencies. Fold is the same kind of object to your initial tree as say a matrix is to a vector, or a derivative is to a polynomial.



Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: