SlideShare a Scribd company logo
1 of 29
Download to read offline
Reasoning about laziness

        Johan Tibell
   johan.tibell@gmail.com


        2011-02-12
Laziness

      Haskell is a lazy language
      Functions and data constructors don’t evaluate their
      arguments until they need them
       cond : : Bool −> a −> a −> a
       cond True t e = t
       cond F a l s e t e = e

      Same with local definitions
       abs : : I n t −> I n t
       abs x | x > 0          = x
              | otherwise = neg x
         where n e g x = negate x
Why laziness is important




      Laziness supports modular programming
      Programmer-written functions instead of built-in language
      constructs
      ( | | ) : : Bool −> Bool −> Bool
      True | |      = True
      False | | x = x
Laziness and modularity


   Laziness lets us separate producers and consumers and still get
   efficient execution:
       Generate all solutions (a huge tree structure)
       Find the solution(s) you want

   nextMove : : Board −> Move
   nextMove b = s e l e c t M o v e a l l M o v e s
     where
       allMoves = allMovesFrom b
   The solutions are generated as they are consumed.
Example: summing some numbers


  sum : : [ I n t ] −> I n t
  sum x s = sum ’ 0 x s
    where
      sum ’ a c c [ ]         = acc
      sum ’ a c c ( x : x s ) = sum ’ ( a c c + x ) x s
   foldl abstracts the accumulator recursion pattern:
   f o l d l : : ( a −> b −> a ) −> a −> [ b ] −> a
   foldl f z []             = z
   f o l d l f z ( x : xs ) = f o l d l f ( f z x ) xs

  sum = f o l d l (+) 0
A misbehaving function

   How does evaluation of this expression proceed?
   sum [ 1 , 2 , 3 ]
   Like this:

   sum   [1,2,3]
   ==>   foldl (+) 0 [1,2,3]
   ==>   foldl (+) (0+1) [2,3]
   ==>   foldl (+) ((0+1)+2) [3]
   ==>   foldl (+) (((0+1)+2)+3) []
   ==>   ((0+1)+2)+3
   ==>   (1+2)+3
   ==>   3+3
   ==>   6
Thunks



  A thunk represents an unevaluated expression.
      GHC needs to store all the unevaluated + expressions on the
      heap, until their value is needed.
      Storing and evaluating thunks is costly, and unnecessary if the
      expression was going to be evaluated anyway.
      foldl allocates n thunks, one for each addition, causing a
      stack overflow when GHC tries to evaluate the chain of
      thunks.
Controlling evaluation order




   The seq function allows to control evaluation order.
   seq : : a −> b −> b
   Informally, when evaluated, the expression seq a b evaluates a and
   then returns b.
Weak head normal form



  Evaluation stops as soon as a data constructor (or lambda) is
  reached:

  ghci> seq (1 ‘div‘ 0) 2
  *** Exception: divide by zero
  ghci> seq ((1 ‘div‘ 0), 3) 2
  2


  We say that seq evaluates to weak head normal form (WHNF).
Weak head normal form



  Forcing the evaluation of an expression using seq only makes sense
  if the result of that expression is used later:
   l e t x = 1 + 2 i n seq x ( f x )
  The expression
   p r i n t ( seq ( 1 + 2 ) 3 )
  doesn’t make sense as the result of 1+2 is never used.
Exercise




   Rewrite the expression
   (1 + 2 , ’ a ’ )
   so that the component of the pair is evaluated before the pair is
   created.
Solution




   Rewrite the expression as
   l e t x = 1 + 2 i n seq x ( x , ’ a ’ )
A strict left fold




   We want to evaluate the expression f z x before evaluating the
   recursive call:
    f o l d l ’ : : ( a −> b −> a ) −> a −> [ b ] −> a
    foldl ’ f z [ ]          = z
    foldl ’ f z ( x : xs ) = l e t z ’ = f z x
                               i n seq z ’ ( f o l d l ’ f z ’ x s )
Summing numbers, attempt 2

  How does evaluation of this expression proceed?

  foldl’ (+) 0 [1,2,3]

  Like this:

  foldl’ (+)      0 [1,2,3]
  ==> foldl’      (+) 1 [2,3]
  ==> foldl’      (+) 3 [3]
  ==> foldl’      (+) 6 []
  ==> 6

  Sanity check:

  ghci> print (foldl’ (+) 0 [1..1000000])
  500000500000
Computing the mean

  A function that computes the mean of a list of numbers:
  mean : : [ Double ] −> Double
  mean x s = s / f r o m I n t e g r a l l
    where
      ( s , l ) = f o l d l ’ s t e p (0 , 0) xs
      s t e p ( s , l ) a = ( s+a , l +1)
  We compute the length of the list and the sum of the numbers in
  one pass.

  $ ./Mean
  Stack space overflow: current size 8388608 bytes.
  Use ‘+RTS -Ksize -RTS’ to increase it.

  Didn’t we just fix that problem?!?
seq and data constructors


   Remember:
       Data constructors don’t evaluate their arguments when
       created
       seq only evaluates to the outmost data constructor, but
       doesn’t evaluate its arguments
   Problem: foldl ’ forces the evaluation of the pair constructor, but
   not its arguments, causing unevaluated thunks build up inside the
   pair:

   (0.0 + 1.0 + 2.0 + 3.0, 0 + 1 + 1 + 1)
Forcing evaluation of constructor arguments



   We can force GHC to evaluate the constructor arguments before
   the constructor is created:
   mean : : [ Double ] −> Double
   mean x s = s / f r o m I n t e g r a l l
     where
       ( s , l ) = f o l d l ’ s t e p (0 , 0) xs
       step (s , l ) a = let s ’ = s + a
                                      l ’ = l + 1
                               i n seq s ’ ( seq l ’ ( s ’ , l ’ ) )
Bang patterns


   A bang patterns is a concise way to express that an argument
   should be evaluated.
   {−# LANGUAGE B a n g P a t t e r n s #−}

   mean : : [ Double ] −> Double
   mean x s = s / f r o m I n t e g r a l l
     where
       ( s , l ) = f o l d l ’ s t e p (0 , 0) xs
       s t e p ( ! s , ! l ) a = ( s + a , l + 1)
   s and l are evaluated before the right-hand side of step is
   evaluated.
Strictness



   We say that a function is strict in an argument, if evaluating the
   function always causes the argument to be evaluated.
   n u l l : : [ a ] −> Bool
   n u l l [ ] = True
   null        = False
   null is strict in its first (and only) argument, as it needs to be
   evaluated to pick a return value.
Strictness - Example



   cond is strict in the first argument, but not in the second and third
   argument:
   cond : : Bool −> a −> a −> a
   cond True t e = t
   cond F a l s e t e = e
   Reason: Each of the two branches only evaluate one of the two
   last arguments to cond.
Strict data types




   Haskell lets us say that we always want the arguments of a
   constructor to be evaluated:
   data P a i r S a b = PS ! a ! b
   When a PairS is evaluated, its arguments are evaluated.
Strict pairs as accumulators



   We can use a strict pair to simplify our mean function:
   mean : : [ Double ] −> Double
   mean x s = s / f r o m I n t e g r a l l
     where
       PS s l = f o l d l ’ s t e p ( PS 0 0 ) x s
       s t e p ( PS s l ) a = PS ( s + a ) ( l + 1 )
   Tip: Prefer strict data types when laziness is not needed for your
   program to work correctly.
Reasoning about laziness



   A function application is only evaluated if its result is needed,
   therefore:
        One of the function’s right-hand sides will be evaluated.
        Any expression whose value is required to decide which RHS
        to evaluate, must be evaluated.
   By using this “backward-to-front” analysis we can figure which
   arguments a function is strict in.
Reasoning about laziness: example



   max : : I n t −> I n t   −> I n t
   max x y
       | x > y         =    x
       | x < y         =    y
       | otherwise =        x   −− a r b i t r a r y

       To pick one of the three RHS, we must evaluate x > y.
       Therefore we must evaluate both x and y.
       Therefore max is strict in both x and y.
Poll

   data BST = L e a f | Node I n t BST BST

   i n s e r t : : I n t −> BST −> BST
   insert x Leaf               = Node x L e a f L e a f
   i n s e r t x ( Node x ’ l r )
           | x < x’            = Node x ’ ( i n s e r t x l ) r
           | x > x’            = Node x ’ l ( i n s e r t x r )
           | o t h e r w i s e = Node x l r
   Which arguments is insert strict in?
       None
       1st
       2nd
       Both
Solution



   Only the second, as inserting into an empty tree can be done
   without comparing the value being inserted. For example, this
   expression
   i n s e r t ( 1 ‘ div ‘ 0 ) L e a f
   does not raise a division-by-zero expression but
   i n s e r t ( 1 ‘ div ‘ 0 ) ( Node 2 L e a f L e a f )
   does.
Some other things worth pointing out




      insert x l is not evaluated before the Node is created, so it’s
      stored as a thunk.
      Most tree based data structures use strict sub-trees:
      data S e t a = Tip
                   | Bin ! S i z e a ! ( S e t a ) ! ( S e t a )
Strict function arguments are great for performance




       Strict arguments can often be passed as unboxed values (e.g.
       a machine integer in a register instead of a pointer to an
       integer on the heap).
       The compiler can often infer which arguments are stricts, but
       can sometimes need a little help (like in the case of insert a
       few slides back).
Summary




  Understanding how evaluation works in Haskell is important and
  requires practice.

More Related Content

What's hot

Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskellLuca Molteni
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaPhilip Schwarz
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScriptWebF
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaSierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Bryan O'Sullivan
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
 

What's hot (20)

Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaSierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 

Viewers also liked

Dealing with laziness michael's ppt
Dealing with laziness  michael's pptDealing with laziness  michael's ppt
Dealing with laziness michael's pptlearningforalifetime
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional WorldDebasish Ghosh
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
February 19 2017 -Overcoming Laziness
February 19 2017 -Overcoming LazinessFebruary 19 2017 -Overcoming Laziness
February 19 2017 -Overcoming LazinessCatherine Lirio
 
Innovation - Laziness
Innovation - LazinessInnovation - Laziness
Innovation - Lazinessvicky727r
 
What Causes Laziness? - By Simeon Adedokun
What Causes Laziness? - By Simeon AdedokunWhat Causes Laziness? - By Simeon Adedokun
What Causes Laziness? - By Simeon AdedokunSimeon Adedokun
 
How to Stop Being Lazy - Short Tutorials
How to Stop Being Lazy - Short TutorialsHow to Stop Being Lazy - Short Tutorials
How to Stop Being Lazy - Short TutorialsTansika Malar
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monadskenbot
 
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Chris Richardson
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Research Paper on Academic Cheating
Research Paper on Academic CheatingResearch Paper on Academic Cheating
Research Paper on Academic CheatingGrace Andoyo
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Andrey Breslav
 
Анонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковАнонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковЮрий Сыровецкий
 
Монады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвМонады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвЮрий Сыровецкий
 

Viewers also liked (20)

The Myth of Laziness
The Myth of Laziness The Myth of Laziness
The Myth of Laziness
 
Dealing with laziness michael's ppt
Dealing with laziness  michael's pptDealing with laziness  michael's ppt
Dealing with laziness michael's ppt
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Thesis writing manual
Thesis writing manualThesis writing manual
Thesis writing manual
 
February 19 2017 -Overcoming Laziness
February 19 2017 -Overcoming LazinessFebruary 19 2017 -Overcoming Laziness
February 19 2017 -Overcoming Laziness
 
Innovation - Laziness
Innovation - LazinessInnovation - Laziness
Innovation - Laziness
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
What Causes Laziness? - By Simeon Adedokun
What Causes Laziness? - By Simeon AdedokunWhat Causes Laziness? - By Simeon Adedokun
What Causes Laziness? - By Simeon Adedokun
 
How to Stop Being Lazy - Short Tutorials
How to Stop Being Lazy - Short TutorialsHow to Stop Being Lazy - Short Tutorials
How to Stop Being Lazy - Short Tutorials
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Research Paper on Academic Cheating
Research Paper on Academic CheatingResearch Paper on Academic Cheating
Research Paper on Academic Cheating
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?
 
Анонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковАнонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита Волков
 
Монады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвМонады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон Холомьёв
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 

Similar to Reasoning about laziness

Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals reviewElifTech
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxDevaraj Chilakala
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data ManipulationChu An
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idrisConor Farrell
 
Asymptotic Notation and Complexity
Asymptotic Notation and ComplexityAsymptotic Notation and Complexity
Asymptotic Notation and ComplexityRajandeep Gill
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaFolding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues listsJames Wong
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
StacksqueueslistsFraboni Ec
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsTony Nguyen
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsHarry Potter
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsYoung Alista
 
Dancing Links: an educational pearl
Dancing Links: an educational pearlDancing Links: an educational pearl
Dancing Links: an educational pearlESUG
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxagnesdcarey33086
 

Similar to Reasoning about laziness (20)

Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Programming Hp33s talk v3
Programming Hp33s talk v3Programming Hp33s talk v3
Programming Hp33s talk v3
 
bobok
bobokbobok
bobok
 
Array
ArrayArray
Array
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
AlgorithmAnalysis2.ppt
AlgorithmAnalysis2.pptAlgorithmAnalysis2.ppt
AlgorithmAnalysis2.ppt
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
Asymptotic Notation and Complexity
Asymptotic Notation and ComplexityAsymptotic Notation and Complexity
Asymptotic Notation and Complexity
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaFolding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
Stacksqueueslists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Dancing Links: an educational pearl
Dancing Links: an educational pearlDancing Links: an educational pearl
Dancing Links: an educational pearl
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
 

Recently uploaded

4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 

Recently uploaded (20)

4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 

Reasoning about laziness

  • 1. Reasoning about laziness Johan Tibell johan.tibell@gmail.com 2011-02-12
  • 2. Laziness Haskell is a lazy language Functions and data constructors don’t evaluate their arguments until they need them cond : : Bool −> a −> a −> a cond True t e = t cond F a l s e t e = e Same with local definitions abs : : I n t −> I n t abs x | x > 0 = x | otherwise = neg x where n e g x = negate x
  • 3. Why laziness is important Laziness supports modular programming Programmer-written functions instead of built-in language constructs ( | | ) : : Bool −> Bool −> Bool True | | = True False | | x = x
  • 4. Laziness and modularity Laziness lets us separate producers and consumers and still get efficient execution: Generate all solutions (a huge tree structure) Find the solution(s) you want nextMove : : Board −> Move nextMove b = s e l e c t M o v e a l l M o v e s where allMoves = allMovesFrom b The solutions are generated as they are consumed.
  • 5. Example: summing some numbers sum : : [ I n t ] −> I n t sum x s = sum ’ 0 x s where sum ’ a c c [ ] = acc sum ’ a c c ( x : x s ) = sum ’ ( a c c + x ) x s foldl abstracts the accumulator recursion pattern: f o l d l : : ( a −> b −> a ) −> a −> [ b ] −> a foldl f z [] = z f o l d l f z ( x : xs ) = f o l d l f ( f z x ) xs sum = f o l d l (+) 0
  • 6. A misbehaving function How does evaluation of this expression proceed? sum [ 1 , 2 , 3 ] Like this: sum [1,2,3] ==> foldl (+) 0 [1,2,3] ==> foldl (+) (0+1) [2,3] ==> foldl (+) ((0+1)+2) [3] ==> foldl (+) (((0+1)+2)+3) [] ==> ((0+1)+2)+3 ==> (1+2)+3 ==> 3+3 ==> 6
  • 7. Thunks A thunk represents an unevaluated expression. GHC needs to store all the unevaluated + expressions on the heap, until their value is needed. Storing and evaluating thunks is costly, and unnecessary if the expression was going to be evaluated anyway. foldl allocates n thunks, one for each addition, causing a stack overflow when GHC tries to evaluate the chain of thunks.
  • 8. Controlling evaluation order The seq function allows to control evaluation order. seq : : a −> b −> b Informally, when evaluated, the expression seq a b evaluates a and then returns b.
  • 9. Weak head normal form Evaluation stops as soon as a data constructor (or lambda) is reached: ghci> seq (1 ‘div‘ 0) 2 *** Exception: divide by zero ghci> seq ((1 ‘div‘ 0), 3) 2 2 We say that seq evaluates to weak head normal form (WHNF).
  • 10. Weak head normal form Forcing the evaluation of an expression using seq only makes sense if the result of that expression is used later: l e t x = 1 + 2 i n seq x ( f x ) The expression p r i n t ( seq ( 1 + 2 ) 3 ) doesn’t make sense as the result of 1+2 is never used.
  • 11. Exercise Rewrite the expression (1 + 2 , ’ a ’ ) so that the component of the pair is evaluated before the pair is created.
  • 12. Solution Rewrite the expression as l e t x = 1 + 2 i n seq x ( x , ’ a ’ )
  • 13. A strict left fold We want to evaluate the expression f z x before evaluating the recursive call: f o l d l ’ : : ( a −> b −> a ) −> a −> [ b ] −> a foldl ’ f z [ ] = z foldl ’ f z ( x : xs ) = l e t z ’ = f z x i n seq z ’ ( f o l d l ’ f z ’ x s )
  • 14. Summing numbers, attempt 2 How does evaluation of this expression proceed? foldl’ (+) 0 [1,2,3] Like this: foldl’ (+) 0 [1,2,3] ==> foldl’ (+) 1 [2,3] ==> foldl’ (+) 3 [3] ==> foldl’ (+) 6 [] ==> 6 Sanity check: ghci> print (foldl’ (+) 0 [1..1000000]) 500000500000
  • 15. Computing the mean A function that computes the mean of a list of numbers: mean : : [ Double ] −> Double mean x s = s / f r o m I n t e g r a l l where ( s , l ) = f o l d l ’ s t e p (0 , 0) xs s t e p ( s , l ) a = ( s+a , l +1) We compute the length of the list and the sum of the numbers in one pass. $ ./Mean Stack space overflow: current size 8388608 bytes. Use ‘+RTS -Ksize -RTS’ to increase it. Didn’t we just fix that problem?!?
  • 16. seq and data constructors Remember: Data constructors don’t evaluate their arguments when created seq only evaluates to the outmost data constructor, but doesn’t evaluate its arguments Problem: foldl ’ forces the evaluation of the pair constructor, but not its arguments, causing unevaluated thunks build up inside the pair: (0.0 + 1.0 + 2.0 + 3.0, 0 + 1 + 1 + 1)
  • 17. Forcing evaluation of constructor arguments We can force GHC to evaluate the constructor arguments before the constructor is created: mean : : [ Double ] −> Double mean x s = s / f r o m I n t e g r a l l where ( s , l ) = f o l d l ’ s t e p (0 , 0) xs step (s , l ) a = let s ’ = s + a l ’ = l + 1 i n seq s ’ ( seq l ’ ( s ’ , l ’ ) )
  • 18. Bang patterns A bang patterns is a concise way to express that an argument should be evaluated. {−# LANGUAGE B a n g P a t t e r n s #−} mean : : [ Double ] −> Double mean x s = s / f r o m I n t e g r a l l where ( s , l ) = f o l d l ’ s t e p (0 , 0) xs s t e p ( ! s , ! l ) a = ( s + a , l + 1) s and l are evaluated before the right-hand side of step is evaluated.
  • 19. Strictness We say that a function is strict in an argument, if evaluating the function always causes the argument to be evaluated. n u l l : : [ a ] −> Bool n u l l [ ] = True null = False null is strict in its first (and only) argument, as it needs to be evaluated to pick a return value.
  • 20. Strictness - Example cond is strict in the first argument, but not in the second and third argument: cond : : Bool −> a −> a −> a cond True t e = t cond F a l s e t e = e Reason: Each of the two branches only evaluate one of the two last arguments to cond.
  • 21. Strict data types Haskell lets us say that we always want the arguments of a constructor to be evaluated: data P a i r S a b = PS ! a ! b When a PairS is evaluated, its arguments are evaluated.
  • 22. Strict pairs as accumulators We can use a strict pair to simplify our mean function: mean : : [ Double ] −> Double mean x s = s / f r o m I n t e g r a l l where PS s l = f o l d l ’ s t e p ( PS 0 0 ) x s s t e p ( PS s l ) a = PS ( s + a ) ( l + 1 ) Tip: Prefer strict data types when laziness is not needed for your program to work correctly.
  • 23. Reasoning about laziness A function application is only evaluated if its result is needed, therefore: One of the function’s right-hand sides will be evaluated. Any expression whose value is required to decide which RHS to evaluate, must be evaluated. By using this “backward-to-front” analysis we can figure which arguments a function is strict in.
  • 24. Reasoning about laziness: example max : : I n t −> I n t −> I n t max x y | x > y = x | x < y = y | otherwise = x −− a r b i t r a r y To pick one of the three RHS, we must evaluate x > y. Therefore we must evaluate both x and y. Therefore max is strict in both x and y.
  • 25. Poll data BST = L e a f | Node I n t BST BST i n s e r t : : I n t −> BST −> BST insert x Leaf = Node x L e a f L e a f i n s e r t x ( Node x ’ l r ) | x < x’ = Node x ’ ( i n s e r t x l ) r | x > x’ = Node x ’ l ( i n s e r t x r ) | o t h e r w i s e = Node x l r Which arguments is insert strict in? None 1st 2nd Both
  • 26. Solution Only the second, as inserting into an empty tree can be done without comparing the value being inserted. For example, this expression i n s e r t ( 1 ‘ div ‘ 0 ) L e a f does not raise a division-by-zero expression but i n s e r t ( 1 ‘ div ‘ 0 ) ( Node 2 L e a f L e a f ) does.
  • 27. Some other things worth pointing out insert x l is not evaluated before the Node is created, so it’s stored as a thunk. Most tree based data structures use strict sub-trees: data S e t a = Tip | Bin ! S i z e a ! ( S e t a ) ! ( S e t a )
  • 28. Strict function arguments are great for performance Strict arguments can often be passed as unboxed values (e.g. a machine integer in a register instead of a pointer to an integer on the heap). The compiler can often infer which arguments are stricts, but can sometimes need a little help (like in the case of insert a few slides back).
  • 29. Summary Understanding how evaluation works in Haskell is important and requires practice.