SlideShare a Scribd company logo
1 of 81
Download to read offline
recursion and erlang
functionalconf ’14, Bangalore
Bhasker Kode

Helpshift
@bhaskerkode @linesofkode
http://github.com/helpshift
git clone https://github.com/bosky101/fuconf
PART I
HISTORICAL walkthrough recursion
and erlang
automatic computing
Symposium. Germany, October 1955
ACM, US, 1957
goals of the IAL
mathematical notation
printable in publications
“should be able to be translated to
programs”
great strides
agreed upon the BNF
renamed from IAL to Algol
spanned 50 centres and 74 persons
formalized pass by value/reference
agreed to meet in 1960
features
variables
assignment
expressions
selection
iteration
maybe some sort of procedure
clashes
to use “,” or a “.” in numbers ?
US industrial programmers had real-world
inputs and recommendations
pass by reference was confusing
“Add recursion?” Lisp had just added
recursion few months before release
Dijkstra saw the potential of recursion.
With editor Naur, added it secretly to
the draft over phone from Amsterdam.
Hence called the “Amsterdam Plot”
Recursion was a major step. It was
introduced in a sneaky way.
1986
Erlang was designed for writing
concurrent programs that 

“run forever.”
Joe Armstrong at Ericsson Labs.
#telephony 

star #1 on erlang team
expressive
robust
object oriented
concurrency
ecosystem
long running
easy to debug
closures
immutability
single-threaded / multi-threaded
recursion
actor model
hot code loading
language design vs compiler design vs consequences
why concurrency was #1
Idea came from existing telephone exchanges
Lets say there are two separate phone calls
One call going down should not affect the other
They should not share anything, no sharing pointers
So copy data over. beginnings of message passing.
Be able to work on different registers
simultaneously.
thought process
with concurrency as the first goal,
everything thing else was worked out
or a consequences around decisions
around concurrency
concurrency existed before
erlang
• Ada (with tasks)
• EriPascal (an Ericsson dialect of Pascal
with concurrent processes)
• Chill (with processes)
• PLEX (processes implemented in
hardware. Also inspired linking errors)
• and Euclid
#emp2 to #emp1
“3 properties of a programming language
were central to the efficient operation of a
concurrent language or operating system.“
1) the time to create a process.
2) the time to perform a context switch
between two different processes
3) the time to copy a message between two
processes
3 emps
“We rapidly adopted a philosophy of
message passing by copying and no
sharing of data resources. Again, this was
counter to the mood of the time, where
threads and shared resources protected
by semaphores were the dominant way
of programming concurrent systems.”
funny incident
• the 3 employees working on erlang
went to a conference just like this
• asked speakers what would happen if
one of the many machines crashes
• reply was “no failures” or “can’t do
anything” . This was still 1985.
• Joe armstrong first wrote this in the
algebra (hurray for algol 60 )
• a prolog engineer saw the algebra
and said, i can program this
• Joe was amazed. Learned prolog.
• prior to prolog, the implementation in smalltalk
• dial a number, send that as a message to
exchange.
• dial a valid number, other phone should ring
• if its busy, get back busy
• if its not busy, get back not busy
state machines
“the software for call control was best
modeled using finite state machines
that undergo state transitions in
response to protocol messages.”
What started as an experiment in
adding concurrency to Prolog,
became more of a language in its own
right and this language acquired a
name Erlang in 1987.
with concurrency as goal
“we didn’t realise at the time, was that
copying data between processes
increases process isolation, increases
concurrency and simplifies the
construction of distributed systems.”
history contd.
• http://www.erlang-factory.com/
conference/SFBay2010/speakers/
joearmstrong
Mike Williams Employee #2
Employee #1
Employee #3
PART II
under the hood of recursion
• usually a function gets executed and returns to
where it was called

return 1 + foo(a)
• but in a tail optimised function, it effectively
does not have to remember where to go back
to

return tail(1,a)
• #gajini
int r(int x) {

if (x == 1) {

return 1;

}

return x*r(x-1);

}
r(3)

!
!
recursive
int r(int x) {

if (x == 1) {

return 1;

}

return x*r(x-1);

}
r(3)



3 * r(2)

3 * (2 * r(1))

3 * (2 * 1)

3 * 2

6
recursive
int tr(int x,int y){

if (x == 0) {

return y;

}

return tr(x-1, x*y);

}



tr(3,1)

!
!
tail recursive
int tr(int x,int y){

if (x == 0) {

return y;

}

return tr(x-1, x*y);

}



tr(3,1)



tr(3-1, 3 * 1)

tr(2-1, 2 * 3)

tr(1-1, 1 * 6)

6
tail recursive
int r(int x) {

if (x == 1) {

return 1;

}

return x*r(x-1);

}
r(3)



3 * r(2)

3 * (2 * r(1))

3 * (2 * 1)

3 * 2

6
int tr(int x,int y){

if (x == 0) {

return y;

}

return tr(x-1, x*y);

}



tr(3,1)



tr(3-1, 3 * 1)

tr(2-1, 2 * 3)

tr(1-1, 1 * 6)

6
recursive tail recursive
• 3 procedural functions approach
• 1 recursive function approach
• 1 tail recursive function approach
see who is knocking on 3 doors
3 doors. 

“anybody here.no?ok.” x3
“anybody here. 

oh another door.”
“anybody here. 

oh another door”x 3 

oh a backdoor!”
procedural call stack
recursive call stack
tail recursive call stack
3 * r(2)

3 * (2 * r(1))

3 * (2 * 1)

3 * 2

6
tr(3-1, 3 * 1)

tr(2-1, 2 * 3)

tr(1-1, 1 * 6)

6
are these both recursive?
which of these are easier to spawn off ?
which of these are easier to stop midway?

which of these are easier to debug?
3 * r(2)

3 * (2 * r(1))

3 * (2 * 1)

3 * 2

6
tr(3-1, 3 * 1)

tr(2-1, 2 * 3)

tr(1-1, 1 * 6)

6
are these both recursive?
which of these are easier to spawn off ?
which of these are easier to stop midway?

which of these are easier to debug?
recursive
good backtrace
cant change order
recursive
easier to parallelise
Amdahl’s Law
“The speedup of a program using 

multiple processors in parallel computing 

is limited by the time needed 

for the sequential fraction of the program.”
which brings us to 

spawning/forking
PART III
let’s look at some code
what is a daemon
• fair to say a daemon is a long running
process?
• fair to say a long running process is a tail-
recursive function?
rough skeleton for daemon in C
a long running process is
in fact a tail-recursive
function
a daemon in erlang
Does this block the scheduler? is this an infinite loop?
!
Let’s start foo and bar on new processes and see what
happens?!
runs a function as a new process. here
we ask it to spawn both foo, then bar.
spawn
erlang’s scheduler splits CPU time
between multiple concurrent processes
based on the “reductions” ( # times a
function is called)
use 8 cores,
so 8 schedulers
fork and start a daemon
that again does nothing…
as long as the heart is beating, you are alive
same way: as long as a process is 

a) tail-recursive or

b) waiting to receive ( on its inbox )

…it is alive
#expressive #erlang
#expressive #erlang
!
compose to suit
your needs
#expressive 

#erlang
!
tail-recursion

+

network

programming

= killer combo
still think erlang has

hard to read syntax?
busting some erlang mythsbusting some erlang myths
meh
Leslie Lamport , “father of distributed
computing” recent Turing Awardee
said that if you are not representing
your distributed program as a state
machine you’re doing something
wrong.
PART III conclusion
tail resursive functions are the foundation for
processes
processes are the foundation for state
machines
tail recursive functions / processes with sockets
are the foundation for network programming
networking programming is the foundation of
distributed computing.
PART III conclusion
erlang & distributed systems
so in other words, erlang’s strength in
distributed computing can be
indirectly be attributed to supporting
tail recursion
Concurrency comes with its

challenges
parallelism and ordering, another great debate
and tale of priorities and compromises
found in any producer/consumer scenario
1,2,3,4,5,6
1,2
3
4
5
6
5,4,1,2,3,6
eg: ekaf_partition_strategy
}
why state machines
send(Socket, Data)

Foo = receive(Socket)
socket already closed, re-open it
socket already open
data being received currently
data being sent currently
socket closed before sending
socket closed before receiving
timeouts
and lastly, not friendly towards batched sending
“India can never join the G7. Why?”
@linesofkode
“Because if they do, it’ll be the G8”
recursion and erlang #ftw
Bhasker Kode

Helpshift
@bhaskerkode
http://github.com/helpshift
git clone https://github.com/bosky101/fuconf
BONUS PART V 

( if we have time)
are language designers sadists?
weird syntax/semantics

immutable variables
monkey patching
boilerplate code
callback hell

weird stack traces

bad handling of floats
whitespace, colons, semicolons, comma,
arrows
compiler design vs language goals 

vs consequences
expressive
robust
object oriented
concurrency
ecosystem
long running
easy to debug
closures
immutability
single-threaded / multi-threaded
recursion
actor model
language design vs compiler design vs consequences
expressive!
robust!
object oriented!
concurrency!
ecosystem!
long running!
easy to debug!
closures!
immutability!
single-threaded / multi-threaded!
actor model!
recursion!
language design vs compiler design vs consequences
So, No. 

Language designers do not draw joy
making you cringe.
language designer: “i want to be concurrent”
compiler designer: “ok, lets try not bottle necking on resources. that way
it’ll be easier to garbage collect.”
language: ”ok, i’ll favour immutability. this may mean recreating entire
Objects/trees/structures and passing them around. 

OO folks wont like this”
compiler: “btw since variables won’t change, can i re-use the call frame.”
language:”ok. as I need to add the sum of 100 numbers, i’ll create A1=1,
A2=increment(A1), …A100 = increment(A99)”
compiler: that looks too repetitive. use A = increment(100, previous) and
write a recursive fn that calls itself until 0.
concurrency
OO
mutability
recursion
message 

passing
speed
if you were to pick
1 as your top priority
and see its effects
concurrency
OO
mutability
recursion
message 

passing
speed
1
CPS
readability
debugging
tail call 

optimised
threads
1
• Guido, was in favour of not loosing stack
traces, and the fact that tail-call optimised
functions would be tougher to debug
• Trivia Alert! An early contributor to
python was an anonymous lisp hacker
“Amit Prem" who added
map,reduce,lambda to python in 1.0.0
TCO/recursion in other languages
• java compiler doesnt tco
• but scala allows tail recursive functions
• infact if you mention @tailrec it wont
compile until you make the function tail
recursive
• lua compiler does tail call optimisation
TCO/recursion in other languages
• The ECMAScript 4 spec was originally going to add
support for TCO, but it was dropped.
• But ECMAScript 6 does, but it only becomes a
standard mid 2015 ( PS: it also has destructuring
which is cool)
• in C compilers , do tail call optimisation but not
necessarily support tail recursion ( where the last
function is intact the same function )
TCO/recursion in other languages
pseudo-code notes
# not tail call optimised but is recursive

a(n){

….

return 1 + a(n-1)

}
# is tail call optimised but not recursive

a(n){

….

return b(n-1)

}



# is tail call optimised and is recursive

a(n){

….

return a(n-1)

}
• in erlang, if a function a calls b, and a function b
calls a, its memory foot print will never increase.
• infact all process that receive messages need to
be tail-recursive
• this is the fundamental construct behind long
lived processes and building state machines in
erlang
TCO/recursion in erlang
recursion and erlang #ftw
Bhasker Kode

Helpshift
@bhaskerkode
http://github.com/helpshift
git clone https://github.com/bosky101/fuconf

More Related Content

What's hot

But we're already open source! Why would I want to bring my code to Apache?
But we're already open source! Why would I want to bring my code to Apache?But we're already open source! Why would I want to bring my code to Apache?
But we're already open source! Why would I want to bring my code to Apache?gagravarr
 
Return oriented programming
Return oriented programmingReturn oriented programming
Return oriented programminghybr1s
 
Erlang For Five Nines
Erlang For Five NinesErlang For Five Nines
Erlang For Five NinesBarcamp Cork
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to ErlangKen Pratt
 
Flink history, roadmap and vision
Flink history, roadmap and visionFlink history, roadmap and vision
Flink history, roadmap and visionStephan Ewen
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkAljoscha Krettek
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthingtonoscon2007
 
Atlanta Spark User Meetup 09 22 2016
Atlanta Spark User Meetup 09 22 2016Atlanta Spark User Meetup 09 22 2016
Atlanta Spark User Meetup 09 22 2016Chris Fregly
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Igalia
 
Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey J On The Beach
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Carlos Miguel Ferreira
 
Tensorflow on Android
Tensorflow on AndroidTensorflow on Android
Tensorflow on AndroidKoan-Sin Tan
 
CILK/CILK++ and Reducers
CILK/CILK++ and ReducersCILK/CILK++ and Reducers
CILK/CILK++ and ReducersYunming Zhang
 
1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTP1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTPJordi Llonch
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + ScalaShouheng Yi
 
Exploit techniques and mitigation
Exploit techniques and mitigationExploit techniques and mitigation
Exploit techniques and mitigationYaniv Shani
 
Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...
Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...
Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...DigitalOcean
 

What's hot (20)

But we're already open source! Why would I want to bring my code to Apache?
But we're already open source! Why would I want to bring my code to Apache?But we're already open source! Why would I want to bring my code to Apache?
But we're already open source! Why would I want to bring my code to Apache?
 
Return oriented programming
Return oriented programmingReturn oriented programming
Return oriented programming
 
Erlang For Five Nines
Erlang For Five NinesErlang For Five Nines
Erlang For Five Nines
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to Erlang
 
Return oriented programming (ROP)
Return oriented programming (ROP)Return oriented programming (ROP)
Return oriented programming (ROP)
 
Flink history, roadmap and vision
Flink history, roadmap and visionFlink history, roadmap and vision
Flink history, roadmap and vision
 
Ruby Under The Hood
Ruby Under The HoodRuby Under The Hood
Ruby Under The Hood
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on Flink
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthington
 
Atlanta Spark User Meetup 09 22 2016
Atlanta Spark User Meetup 09 22 2016Atlanta Spark User Meetup 09 22 2016
Atlanta Spark User Meetup 09 22 2016
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
 
Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.
 
Tensorflow on Android
Tensorflow on AndroidTensorflow on Android
Tensorflow on Android
 
CILK/CILK++ and Reducers
CILK/CILK++ and ReducersCILK/CILK++ and Reducers
CILK/CILK++ and Reducers
 
1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTP1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTP
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + Scala
 
Exploit techniques and mitigation
Exploit techniques and mitigationExploit techniques and mitigation
Exploit techniques and mitigation
 
Numba Overview
Numba OverviewNumba Overview
Numba Overview
 
Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...
Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...
Escape the Walls of PaaS: Unlock the Power & Flexibility of DigitalOcean App ...
 

Similar to Recursion & Erlang, FunctionalConf 14, Bangalore

"Hints" talk at Walchand College Sangli, March 2017
"Hints" talk at Walchand College Sangli, March 2017"Hints" talk at Walchand College Sangli, March 2017
"Hints" talk at Walchand College Sangli, March 2017Neeran Karnik
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongPROIDEA
 
Keynote joearmstrong
Keynote joearmstrongKeynote joearmstrong
Keynote joearmstrongSentifi
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...
Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...
Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...siouxhotornot
 
Natural language processing open seminar For Tensorflow usage
Natural language processing open seminar For Tensorflow usageNatural language processing open seminar For Tensorflow usage
Natural language processing open seminar For Tensorflow usagehyunyoung Lee
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017Codemotion
 
Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with ClojureJohn Stevenson
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCAFxX
 
The Ruby Plumber's Guide to *nix
The Ruby Plumber's Guide to *nixThe Ruby Plumber's Guide to *nix
The Ruby Plumber's Guide to *nixEleanor McHugh
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!C4Media
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#Talbott Crowell
 
First compailer written
First compailer writtenFirst compailer written
First compailer writtenmicrowoorkers
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 

Similar to Recursion & Erlang, FunctionalConf 14, Bangalore (20)

"Hints" talk at Walchand College Sangli, March 2017
"Hints" talk at Walchand College Sangli, March 2017"Hints" talk at Walchand College Sangli, March 2017
"Hints" talk at Walchand College Sangli, March 2017
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
 
Keynote joearmstrong
Keynote joearmstrongKeynote joearmstrong
Keynote joearmstrong
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...
Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...
Sioux Hot-or-Not: Functional programming: unlocking the real power of multi-c...
 
Natural language processing open seminar For Tensorflow usage
Natural language processing open seminar For Tensorflow usageNatural language processing open seminar For Tensorflow usage
Natural language processing open seminar For Tensorflow usage
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
A Peek into TFRT
A Peek into TFRTA Peek into TFRT
A Peek into TFRT
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017Thinking Functionally - John Stevenson - Codemotion Rome 2017
Thinking Functionally - John Stevenson - Codemotion Rome 2017
 
Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with Clojure
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flattening
 
The Ruby Plumber's Guide to *nix
The Ruby Plumber's Guide to *nixThe Ruby Plumber's Guide to *nix
The Ruby Plumber's Guide to *nix
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
 
First compailer written
First compailer writtenFirst compailer written
First compailer written
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
ForLoops.pptx
ForLoops.pptxForLoops.pptx
ForLoops.pptx
 

More from Bhasker Kode

Parsing binaries and protocols with erlang
Parsing binaries and protocols with erlangParsing binaries and protocols with erlang
Parsing binaries and protocols with erlangBhasker Kode
 
thinking in key value stores
thinking in key value storesthinking in key value stores
thinking in key value storesBhasker Kode
 
hover.in at CUFP 2009
hover.in at CUFP 2009hover.in at CUFP 2009
hover.in at CUFP 2009Bhasker Kode
 
in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09Bhasker Kode
 
erlang at hover.in , Devcamp Blr 09
erlang at hover.in , Devcamp Blr 09erlang at hover.in , Devcamp Blr 09
erlang at hover.in , Devcamp Blr 09Bhasker Kode
 
end user programming & yahoo pipes
end user programming & yahoo pipesend user programming & yahoo pipes
end user programming & yahoo pipesBhasker Kode
 
Overview of End-user Programming | Talk at DesignCamp Bangalore
Overview of End-user Programming | Talk at DesignCamp BangaloreOverview of End-user Programming | Talk at DesignCamp Bangalore
Overview of End-user Programming | Talk at DesignCamp BangaloreBhasker Kode
 

More from Bhasker Kode (7)

Parsing binaries and protocols with erlang
Parsing binaries and protocols with erlangParsing binaries and protocols with erlang
Parsing binaries and protocols with erlang
 
thinking in key value stores
thinking in key value storesthinking in key value stores
thinking in key value stores
 
hover.in at CUFP 2009
hover.in at CUFP 2009hover.in at CUFP 2009
hover.in at CUFP 2009
 
in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09in-memory capacity planning, Erlang Factory London 09
in-memory capacity planning, Erlang Factory London 09
 
erlang at hover.in , Devcamp Blr 09
erlang at hover.in , Devcamp Blr 09erlang at hover.in , Devcamp Blr 09
erlang at hover.in , Devcamp Blr 09
 
end user programming & yahoo pipes
end user programming & yahoo pipesend user programming & yahoo pipes
end user programming & yahoo pipes
 
Overview of End-user Programming | Talk at DesignCamp Bangalore
Overview of End-user Programming | Talk at DesignCamp BangaloreOverview of End-user Programming | Talk at DesignCamp Bangalore
Overview of End-user Programming | Talk at DesignCamp Bangalore
 

Recently uploaded

QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 

Recently uploaded (20)

QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 

Recursion & Erlang, FunctionalConf 14, Bangalore

  • 1. recursion and erlang functionalconf ’14, Bangalore Bhasker Kode
 Helpshift @bhaskerkode @linesofkode http://github.com/helpshift git clone https://github.com/bosky101/fuconf
  • 2. PART I HISTORICAL walkthrough recursion and erlang
  • 3. automatic computing Symposium. Germany, October 1955 ACM, US, 1957
  • 4. goals of the IAL mathematical notation printable in publications “should be able to be translated to programs”
  • 5. great strides agreed upon the BNF renamed from IAL to Algol spanned 50 centres and 74 persons formalized pass by value/reference agreed to meet in 1960
  • 7. clashes to use “,” or a “.” in numbers ? US industrial programmers had real-world inputs and recommendations pass by reference was confusing “Add recursion?” Lisp had just added recursion few months before release
  • 8. Dijkstra saw the potential of recursion. With editor Naur, added it secretly to the draft over phone from Amsterdam. Hence called the “Amsterdam Plot” Recursion was a major step. It was introduced in a sneaky way.
  • 9. 1986 Erlang was designed for writing concurrent programs that 
 “run forever.” Joe Armstrong at Ericsson Labs. #telephony 
 star #1 on erlang team
  • 10. expressive robust object oriented concurrency ecosystem long running easy to debug closures immutability single-threaded / multi-threaded recursion actor model hot code loading language design vs compiler design vs consequences
  • 11. why concurrency was #1 Idea came from existing telephone exchanges Lets say there are two separate phone calls One call going down should not affect the other They should not share anything, no sharing pointers So copy data over. beginnings of message passing. Be able to work on different registers simultaneously.
  • 12. thought process with concurrency as the first goal, everything thing else was worked out or a consequences around decisions around concurrency
  • 13. concurrency existed before erlang • Ada (with tasks) • EriPascal (an Ericsson dialect of Pascal with concurrent processes) • Chill (with processes) • PLEX (processes implemented in hardware. Also inspired linking errors) • and Euclid
  • 14. #emp2 to #emp1 “3 properties of a programming language were central to the efficient operation of a concurrent language or operating system.“ 1) the time to create a process. 2) the time to perform a context switch between two different processes 3) the time to copy a message between two processes
  • 15. 3 emps “We rapidly adopted a philosophy of message passing by copying and no sharing of data resources. Again, this was counter to the mood of the time, where threads and shared resources protected by semaphores were the dominant way of programming concurrent systems.”
  • 16. funny incident • the 3 employees working on erlang went to a conference just like this • asked speakers what would happen if one of the many machines crashes • reply was “no failures” or “can’t do anything” . This was still 1985.
  • 17. • Joe armstrong first wrote this in the algebra (hurray for algol 60 ) • a prolog engineer saw the algebra and said, i can program this • Joe was amazed. Learned prolog.
  • 18. • prior to prolog, the implementation in smalltalk • dial a number, send that as a message to exchange. • dial a valid number, other phone should ring • if its busy, get back busy • if its not busy, get back not busy
  • 19. state machines “the software for call control was best modeled using finite state machines that undergo state transitions in response to protocol messages.”
  • 20. What started as an experiment in adding concurrency to Prolog, became more of a language in its own right and this language acquired a name Erlang in 1987.
  • 21. with concurrency as goal “we didn’t realise at the time, was that copying data between processes increases process isolation, increases concurrency and simplifies the construction of distributed systems.”
  • 26. PART II under the hood of recursion
  • 27. • usually a function gets executed and returns to where it was called
 return 1 + foo(a) • but in a tail optimised function, it effectively does not have to remember where to go back to
 return tail(1,a) • #gajini
  • 28. int r(int x) {
 if (x == 1) {
 return 1;
 }
 return x*r(x-1);
 } r(3)
 ! ! recursive
  • 29. int r(int x) {
 if (x == 1) {
 return 1;
 }
 return x*r(x-1);
 } r(3)
 
 3 * r(2)
 3 * (2 * r(1))
 3 * (2 * 1)
 3 * 2
 6 recursive
  • 30. int tr(int x,int y){
 if (x == 0) {
 return y;
 }
 return tr(x-1, x*y);
 }
 
 tr(3,1)
 ! ! tail recursive
  • 31. int tr(int x,int y){
 if (x == 0) {
 return y;
 }
 return tr(x-1, x*y);
 }
 
 tr(3,1)
 
 tr(3-1, 3 * 1)
 tr(2-1, 2 * 3)
 tr(1-1, 1 * 6)
 6 tail recursive
  • 32. int r(int x) {
 if (x == 1) {
 return 1;
 }
 return x*r(x-1);
 } r(3)
 
 3 * r(2)
 3 * (2 * r(1))
 3 * (2 * 1)
 3 * 2
 6 int tr(int x,int y){
 if (x == 0) {
 return y;
 }
 return tr(x-1, x*y);
 }
 
 tr(3,1)
 
 tr(3-1, 3 * 1)
 tr(2-1, 2 * 3)
 tr(1-1, 1 * 6)
 6 recursive tail recursive
  • 33. • 3 procedural functions approach • 1 recursive function approach • 1 tail recursive function approach see who is knocking on 3 doors
  • 34. 3 doors. 
 “anybody here.no?ok.” x3
  • 35. “anybody here. 
 oh another door.”
  • 36. “anybody here. 
 oh another door”x 3 
 oh a backdoor!”
  • 40. 3 * r(2)
 3 * (2 * r(1))
 3 * (2 * 1)
 3 * 2
 6 tr(3-1, 3 * 1)
 tr(2-1, 2 * 3)
 tr(1-1, 1 * 6)
 6 are these both recursive? which of these are easier to spawn off ? which of these are easier to stop midway?
 which of these are easier to debug?
  • 41. 3 * r(2)
 3 * (2 * r(1))
 3 * (2 * 1)
 3 * 2
 6 tr(3-1, 3 * 1)
 tr(2-1, 2 * 3)
 tr(1-1, 1 * 6)
 6 are these both recursive? which of these are easier to spawn off ? which of these are easier to stop midway?
 which of these are easier to debug? recursive good backtrace cant change order recursive easier to parallelise
  • 42. Amdahl’s Law “The speedup of a program using 
 multiple processors in parallel computing 
 is limited by the time needed 
 for the sequential fraction of the program.”
  • 43. which brings us to 
 spawning/forking PART III let’s look at some code
  • 44. what is a daemon • fair to say a daemon is a long running process? • fair to say a long running process is a tail- recursive function?
  • 45. rough skeleton for daemon in C
  • 46. a long running process is in fact a tail-recursive function a daemon in erlang
  • 47. Does this block the scheduler? is this an infinite loop? ! Let’s start foo and bar on new processes and see what happens?!
  • 48. runs a function as a new process. here we ask it to spawn both foo, then bar. spawn
  • 49. erlang’s scheduler splits CPU time between multiple concurrent processes based on the “reductions” ( # times a function is called) use 8 cores, so 8 schedulers
  • 50. fork and start a daemon that again does nothing…
  • 51. as long as the heart is beating, you are alive same way: as long as a process is 
 a) tail-recursive or
 b) waiting to receive ( on its inbox )
 …it is alive
  • 55. still think erlang has
 hard to read syntax? busting some erlang mythsbusting some erlang myths
  • 56. meh
  • 57. Leslie Lamport , “father of distributed computing” recent Turing Awardee said that if you are not representing your distributed program as a state machine you’re doing something wrong. PART III conclusion
  • 58. tail resursive functions are the foundation for processes processes are the foundation for state machines tail recursive functions / processes with sockets are the foundation for network programming networking programming is the foundation of distributed computing. PART III conclusion
  • 59. erlang & distributed systems so in other words, erlang’s strength in distributed computing can be indirectly be attributed to supporting tail recursion
  • 60. Concurrency comes with its
 challenges
  • 61. parallelism and ordering, another great debate and tale of priorities and compromises found in any producer/consumer scenario 1,2,3,4,5,6 1,2 3 4 5 6 5,4,1,2,3,6 eg: ekaf_partition_strategy }
  • 62. why state machines send(Socket, Data)
 Foo = receive(Socket)
  • 63. socket already closed, re-open it socket already open data being received currently data being sent currently socket closed before sending socket closed before receiving timeouts and lastly, not friendly towards batched sending
  • 64. “India can never join the G7. Why?” @linesofkode
  • 65. “Because if they do, it’ll be the G8” recursion and erlang #ftw Bhasker Kode
 Helpshift @bhaskerkode http://github.com/helpshift git clone https://github.com/bosky101/fuconf
  • 66. BONUS PART V 
 ( if we have time) are language designers sadists?
  • 67. weird syntax/semantics
 immutable variables monkey patching boilerplate code callback hell
 weird stack traces
 bad handling of floats whitespace, colons, semicolons, comma, arrows
  • 68. compiler design vs language goals 
 vs consequences
  • 69. expressive robust object oriented concurrency ecosystem long running easy to debug closures immutability single-threaded / multi-threaded recursion actor model language design vs compiler design vs consequences
  • 70. expressive! robust! object oriented! concurrency! ecosystem! long running! easy to debug! closures! immutability! single-threaded / multi-threaded! actor model! recursion! language design vs compiler design vs consequences
  • 71. So, No. 
 Language designers do not draw joy making you cringe.
  • 72. language designer: “i want to be concurrent” compiler designer: “ok, lets try not bottle necking on resources. that way it’ll be easier to garbage collect.” language: ”ok, i’ll favour immutability. this may mean recreating entire Objects/trees/structures and passing them around. 
 OO folks wont like this” compiler: “btw since variables won’t change, can i re-use the call frame.” language:”ok. as I need to add the sum of 100 numbers, i’ll create A1=1, A2=increment(A1), …A100 = increment(A99)” compiler: that looks too repetitive. use A = increment(100, previous) and write a recursive fn that calls itself until 0.
  • 73. concurrency OO mutability recursion message 
 passing speed if you were to pick 1 as your top priority and see its effects
  • 76. • Guido, was in favour of not loosing stack traces, and the fact that tail-call optimised functions would be tougher to debug • Trivia Alert! An early contributor to python was an anonymous lisp hacker “Amit Prem" who added map,reduce,lambda to python in 1.0.0 TCO/recursion in other languages
  • 77. • java compiler doesnt tco • but scala allows tail recursive functions • infact if you mention @tailrec it wont compile until you make the function tail recursive • lua compiler does tail call optimisation TCO/recursion in other languages
  • 78. • The ECMAScript 4 spec was originally going to add support for TCO, but it was dropped. • But ECMAScript 6 does, but it only becomes a standard mid 2015 ( PS: it also has destructuring which is cool) • in C compilers , do tail call optimisation but not necessarily support tail recursion ( where the last function is intact the same function ) TCO/recursion in other languages
  • 79. pseudo-code notes # not tail call optimised but is recursive
 a(n){
 ….
 return 1 + a(n-1)
 } # is tail call optimised but not recursive
 a(n){
 ….
 return b(n-1)
 }
 
 # is tail call optimised and is recursive
 a(n){
 ….
 return a(n-1)
 }
  • 80. • in erlang, if a function a calls b, and a function b calls a, its memory foot print will never increase. • infact all process that receive messages need to be tail-recursive • this is the fundamental construct behind long lived processes and building state machines in erlang TCO/recursion in erlang
  • 81. recursion and erlang #ftw Bhasker Kode
 Helpshift @bhaskerkode http://github.com/helpshift git clone https://github.com/bosky101/fuconf