3 ms·
There's a great (and readable) paper [1] that provides a really strong motivation for TCO in my opinion: the paper shows how to make a language for describing f
by ashton314 2y ago
There's a great (and readable) paper [1] that provides a really strong motivation for TCO in my opinion: the paper shows how to make a language for describing finite state machines with macros. The surface-syntax gets transformed by the macro system into tail-recursive function calls. Without TCO, there's a limit to the number of states you can walk between before your stack gets full. With TCO, you can naturally transition between states without any issue.
Can you build a FSM with, say, an object? Of course. Encoding a FSM with functions comes with benefits though. A big one is that it's harder to get a state encoding error: if you represent your state with an integer, string, or atom, then any value of the right type would suffice, and you could transition to a "state" that doesn't exist. (A good type system can mitigate this significantly.) With functions, however, you'd get a compile-time check that all your states exist.
It's nice having a choice between different ways of encoding FSMs and other constructs. This is probably my biggest beef with Python: a limitation that doesn't exist in other languages that changes how I have to write my code.
I have run into this stack limit in real code. I was building a little classical AI program (might have been negamax; might have been some other search algorithm) and I found a beautiful tail-recursive solution. It was pure and functional and easy to test. It worked on my little test cases, but blew up with a stack error when I ran it on the full-size problem. Had to refactor my code to use some ugly state. Booooo
[1]: Krishnamurthi, Shriram. Educational pearl: Automata via Macros. Journal of Functional Programming. 2006
- Jtsummers 2y agohttps://cs.brown.edu/~sk/Publications/Papers/Published/sk-automata-macros/ https://cs.brown.edu/~sk/Publications/Papers/Published/sk-au...