johnynek / bosatsu

A python-ish pure and total functional programming language
Apache License 2.0
226 stars 11 forks source link

rewrite some closures to just be normal functions #1258

Open johnynek opened 1 week ago

johnynek commented 1 week ago

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 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.