lazy sequences
DESCRIPTION
Lazy sequences, examples in Clojure Functional ProgrammingTRANSCRIPT
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.
When to be lazy?
• When producing large, infinite or variable-sized sequences.
Fibonacci
Fibonacci Definiton
• Base : F0 = 0 ; F1 = 1• Induction : For n > 1 , Fn = Fn-1 + Fn-2
Non Lazy
Lazy
Lazy – Even better
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.
PseudoCode
• a = fibo[1000000]• if true return a• else return
PseudoCode
• So, if it is false, why do I need to calculate fibo[1000000] , if I won´t use it?
• Be Lazy
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)