Tail call optimisation requires accumulator? #2713
Replies: 3 comments 6 replies
-
That's right! Often you need to have a new argument to hold that data that would previously be on the stack frame. |
Beta Was this translation helpful? Give feedback.
-
There are special cases where we don't need an accumulator, such as: /// ♾️
fn loop(callback) {
callback()
loop(callback)
} which is equivalent to the following TypeScript (except for the mutable params): /** ♾️ */
const loop: (callback: CallableFunction) => never = callback => {
while (true)
callback()
} Notice how TS doesn't support retroactive type-inference, so we must specify the type of If we wrote this instead: /// ♾️
fn loop(cb: fn() -> Nil) {
cb()
loop(cb)
} we would get: /** ♾️ */
const loop: (cb: () => undefined) => never = cb => {
while (true)
cb()
} Which forces API consumers to always pass callbacks that return nothing, instead of anything. Please keep in mind that JS/TS |
Beta Was this translation helpful? Give feedback.
-
Coming from scala, that function looks very tail recursive to me 🤔 In scala it would be object TailRec {
@scala.annotation.tailrec
def more_than_n(my_list: List[Int], item: Int, n: Int): Boolean = (my_list, n) match {
case (_, n) if (n < 0) => true
case (List(), _) => false
case (i :: rest, n) if (i == item) => more_than_n(rest, item, n-1)
case (_ :: rest, n) => more_than_n(rest, item, n)
}
} which the compiler accepts according to godbolt https://godbolt.org/z/M3fh6MqM8. Are there some extra rules one must adhere to in Gleam compared to Scala in order to trigger tail call optimization? |
Beta Was this translation helpful? Give feedback.
-
Hello, I'm just learning programming, so please excuse me if this is not the place for such questions.
From what Bing AI told me this function will not make Gleam compiler use tail call optimisation, because it needs an accumulator. Is it the case that Gleam requires a helper function for TCO?
Beta Was this translation helpful? Give feedback.
All reactions