why we need tail calls? · 2017-07-19 · c and ml were both finished in 1973. ml had first-class...

26
Why We Need Tail Calls? Senthil Porunan

Upload: others

Post on 15-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Why We Need Tail Calls? Senthil Porunan

Why We Need Tail Calls ?

©2017 PayPal Inc. Confidential and proprietary.

3

History

Tail Call Optimization

Trampoline

Support

Agenda

HISTORY

©2017 PayPal Inc. Confidential and proprietary.

4

5

Edsger W. Dijkstra

(1930-2002)

Quality of programmers is a decreasing function

of the density of goto statements in the

programs they produce.

6

─Edsger W. Dijkstra

I became convinced that go to statement should

be abolished from all higher level programming

languages.

7

Scheme language

• 1970s

• Tail call Optimization

C and ML were both finished in

1973. ML had first-class functions,

GC, type inference, algebraic data

types, pattern matching, tail-calls

and exceptions.

8

─ Gary Bernhardt

Tail Call Optimization

©2017 PayPal Inc. Confidential and proprietary.

9

Execution Context without tail-call optimization

©2017 PayPal Inc. Confidential and proprietary.

10

GC GC GC GC GC

fact(5,1)

fact(4,5)

fact(5,1)

fact(3,20)

fact(4,5)

fact(5,1) fact(5,1)

fact(4,5)

fact(3,20)

fact(2,60)

GC

fact(5,1)

fact(4,5)

fact(3,20)

fact(2,60)

fact(1,120)

function fact(n, a) {

if (n <= 0) {

return a;

}

return fact(n-1, n *a);

}

11

Without TCO

• Stack growing

• Call stack size

exceeded

Tail Call Optimization in ES6

©2017 PayPal Inc. Confidential and proprietary.

12

GC GC GC

fact(5,1) fact(4,5)

GC

fact(3,20)

GC

fact(2,60)

GC

fact(1,120)

function fact(n, a) {

if (n <= 0) {

return a;

}

return fact(n-1, n *a);

}

13

With TCO

• No Stack Overflow • Constant Space

14

Limitations

15

function factorial(x) {

if (x <= 0) {

return 1;

}

else {

return x * factorial(x-1);

}

}

Stack will grow

function factorial(n) {

return factRec(n, 1);

}

function factRec(x, acc) {

if (x <= 1) {

return acc;

}

else {

return factRec(x-1,

x*acc);

}

}

Constant Stack

16

Why we need tail call optimization ?

Constant Space

17

Trampoline

18

let { trampoline, done, cont } = require('trampoline-js') ;

const _fact = (acc, n) =>

n <= 0 ?

done(acc) :

cont(_fact, acc * n, n - 1)

const fact = trampoline(_fact, 1);

fact(16) //20922789888000

Support

©2017 PayPal Inc. Confidential and proprietary.

19

20

Javascript – ES6

Elixir

Perl

Tcl

Common-Lisp

Language Support

Browser Support

©2017 PayPal Inc. Confidential and proprietary.

21

22

23

“ Programs must be written for people to read, and only incidentally for machines to execute. ”

- Harold Abelson, SICP

Thank You

©2017 PayPal Inc. Confidential and proprietary.

24

Q & A

©2017 PayPal Inc. Confidential and proprietary.

25

www.modsummit.com

www.developersummit.com