-
Notifications
You must be signed in to change notification settings - Fork 12
Open
Description
consider:
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 closes 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.
Metadata
Metadata
Assignees
Labels
No labels