def foldLeft(lst: List[a], item: b, fn: (b, a) -> b) -> b:
# make the loop function as small as possible
def loop(lst, item):
recur lst:
case []: item
case [head, *tail]: loop(tail, fn(item, head))
loop(lst, item)
Here foldLeft clsose over fn but the loop function never escapes. Closures are less efficient in general than functions with no closure, so we could rewrite this to:
def foldLeft(lst: List[a], item: b, fn: (b, a) -> b) -> b:
# make the loop function as small as possible
def loop1(fn, lst, item):
recur lst:
case []: item
case [head, *tail]: loop1(fn, tail, fn(item, head))
loop1(fn, lst, item)
And in this case, since the inner loop doesn't escape, no one can observe a difference, but now loop1 has no closure. Instead, loop1 is just a normal function that also happens to be possible to compile to a while loop.
consider:
Here foldLeft clsose over
fn
but the loop function never escapes. Closures are less efficient in general than functions with no closure, so we could rewrite this to:And in this case, since the inner loop doesn't escape, no one can observe a difference, but now loop1 has no closure. Instead, loop1 is just a normal function that also happens to be possible to compile to a while loop.