Top Banner
Lazy Sequences
13

Lazy sequences

Jun 29, 2015

Download

Technology

Diego Mendonça

Lazy sequences, examples in Clojure
Functional Programming
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lazy sequences

Lazy Sequences

Page 2: Lazy sequences

What is that?

• An expression´s evaluation is postponed until it is actually needed

• Can build complex sequences and pay only for the elements you actually need.

• Lazy techniques imply pure functions.

Page 3: Lazy sequences

When to be lazy?

• When producing large, infinite or variable-sized sequences.

Page 4: Lazy sequences

Fibonacci

Page 5: Lazy sequences

Fibonacci Definiton

• Base : F0 = 0 ; F1 = 1• Induction : For n > 1 , Fn = Fn-1 + Fn-2

Page 6: Lazy sequences

Non Lazy

Page 7: Lazy sequences

Lazy

Page 8: Lazy sequences

Lazy – Even better

Page 9: Lazy sequences

Lazy

• There is no such thing as a free lunch. But with lazy sequences, you can have an infinite menu and pay only for the menu items you are eating at a given moment.

Page 10: Lazy sequences

PseudoCode

• a = fibo[1000000]• if true return a• else return

Page 11: Lazy sequences

PseudoCode

• So, if it is false, why do I need to calculate fibo[1000000] , if I won´t use it?

• Be Lazy

Page 12: Lazy sequences

Some more code

• (def lots-o-fibs (take 1000000000 (fibo)))• This will take a LOT of time, won´t it?

• (nth lots-o-fibs 100)

Page 13: Lazy sequences

Questions?

[email protected]

http://www.linkedin.com/in/diegomendonca