Skip to content

rewrite some closures to just be normal functions #1258

@johnynek

Description

@johnynek

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions