SlideShare uma empresa Scribd logo
1 de 24
Baixar para ler offline
Real World Haskell:
     Lecture 5

   Bryan O’Sullivan


     2009-11-04
Adding quaternions


   We add two quaternions by adding their coefficients.


                     a+         bi +          cj +           dk
       +             w+         xi +          yj +           zk
       =      (a + w ) +   (b + x)i +   (c + y )j +     (d + z)k

   Or, in Haskell:

   addQ (Q a b c d ) (Q w x y z ) =
     Q ( a+w) ( b+x ) ( c+y ) ( d+z )
Subtracting quaternions




   Subtraction is defined similarly.
   subQ (Q a b c d ) (Q w x y z ) =
     Q ( a−w) ( b−x ) ( c−y ) ( d−z )
Typeclass inheritance


   The Eq typeclass that we met last week lets us compare values for
   equality.
   For many values, we want to be able to compare them for (total)
   ordering, for which we use the Ord typeclass.

   c l a s s ( Eq a ) = Ord a where
                       >
       compare : : a −> a −> Ordering

   Notice the constraint on the Ord class: this states that in order for
   a type to be an instance of Ord, it must already be an instance of
   Eq.
The Num typeclass



  Haskell defines a typeclass named Num that lets us express
  common arithmetic operations:
   c l a s s ( Eq a , Show a ) = Num a where
                                >
       (+)        : : a −> a −> a
       (∗)        : : a −> a −> a
       (−)        : : a −> a −> a
       negate : : a −> a
       abs        : : a −> a
       {− e t c . −}
Num and quaternions


  On first glance, we can easily fit our Quaternion type into the
  Num class.
   i n s t a n c e Num Q u a t e r n i o n where
       (+) = addQ
       (−) = subQ
       {− ??? −}
  We quickly run into problems: it’s not obvious what negate or abs
  should do.
  Maybe we can do something with multiplication, though?
Multiplying quaternions


   If we can remember the identities

                        i2 = j2 = k2 = ijk = −1

   Then multiplication of quaternions falls out from the usual laws of
   arithmetic, but takes a complicated form:

     a + bi + cj + dk ∗ w + xi + y j + zk = aw − bx − cy − dz
                                          + (ax + bw + cz − dy )i
                                          + (ay − bz + cw + dx)j
                                          + (az + by − cx + dw )k
Multiplying quaternions in Haskell

   It’s easy to convert our equation into executable form:
   mulQ (Q a b c d )       (Q w x y z )
     = Q ( a ∗w − b∗ x     − c ∗ y − d∗ z )
         ( a ∗ x + b∗w     + c ∗ z − d∗ y )
         ( a ∗ y − b∗ z    + c ∗w + d∗ x )
         ( a ∗ z + b∗ y    − c ∗ x + d∗w)
Multiplying quaternions in Haskell

   It’s easy to convert our equation into executable form:
   mulQ (Q a b c d )         (Q w x y z )
     = Q ( a ∗w − b∗ x       − c ∗ y − d∗ z )
         ( a ∗ x + b∗w       + c ∗ z − d∗ y )
         ( a ∗ y − b∗ z      + c ∗w + d∗ x )
         ( a ∗ z + b∗ y      − c ∗ x + d∗w)

   Does this mean that we should augment our definition of Num as
   follows?
   i n s t a n c e Num Q u a t e r n i o n where
       ( ∗ ) = mulQ
       {− e t c . −}
Arithmetic laws



   There are some laws that are so ingrained into our minds that we
   never think about them:

         m+n =n+m                     (commutative law of addition)
   (m + n) + k = m + (n + k)            (associative law of addition)
            mn = nm             (commutative law of multiplication)
         (mn)k = m(nk)             (associative law of multiplication)
Laws for quaternions
   We can see by simple inspection that addition over quaternions
   must satisfy the commutative and associative laws of normal
   arithmetic.
   We used those familiar arithmetic laws to derive the formula for
   quaternion multiplication, but do quaternions satisfy the
   commutative law of multiplication?

   Prelude> let a = Q 2 0 9 0
   Prelude> let b = Q 0 9 0 2

   Prelude> a ‘mulQ‘ b
   Q 0.0 36.0 0.0 (-77.0)

   Prelude> b ‘mulQ‘ a
   Q 0.0 0.0 0.0 85.0
Laws: made to be broken?


   When you write or use a typeclass, there’s an implied
   understanding that you’ll obey its laws1 .
   Code that uses Eq relies on the fact that if a == b is True, then
   b == a will be True too, and a /= b will be False.
   Similarly, code that uses Num implicitly relies on the
   commutativity and associativity of addition and multiplication.




     1
         Unfortunately, these laws are often undocumented.
Laws: made to be broken?


   When you write or use a typeclass, there’s an implied
   understanding that you’ll obey its laws1 .
   Code that uses Eq relies on the fact that if a == b is True, then
   b == a will be True too, and a /= b will be False.
   Similarly, code that uses Num implicitly relies on the
   commutativity and associativity of addition and multiplication.
   Neither the type system nor any other aspect of Haskell will help
   you to do the heavy lifting here:
          The burden is on you, the creator of a type, to ensure that if
          you make it an instance of a typeclass, that it follows the laws.



     1
         Unfortunately, these laws are often undocumented.
A sketchy approach

   Since quaternion multiplication is not commutative, we should not
   implement (∗). But what more should we do?
   For instance, we could partially implement Num:
   i n s t a n c e Num Q u a t e r n i o n where
           (+) = addQ
            ( ∗ ) = undefined
   What effect does this have on code that tries to use multiplication?

   Prelude> scalar 2 * scalar 3
   *** Exception: Prelude.undefined

   This is not very satisfactory behaviour.
Playing fast and loose

   Of course, Haskell itself doesn’t escape the sin bin. What happens
   to those fancy laws in the presence of inexact arithmetic?

   Prelude> let a = 1e20 :: Double
   Prelude> (a + (-a))   + 1
   1.0
   Prelude> a +   ((-a) + 1)
   0.0

   (This is the same behaviour as every other language that
   implements floating point, by the way.)
   A conclusion? You can violate the rules, but the compiler can’t
   remind you that you’re cheating.
Code that might fail

   You’ve probably seen this behaviour by now:

   Prelude> 1 ‘div‘ 0
   *** Exception: divide by zero

   These exceptions are often annoying, because we can’t easily catch
   and handle them.
   There exists a predefined type we can use to deal with these cases:
   data Maybe a = Nothing
                | Just a
   Notice that this type is parameterized, so we can have types such
   as Maybe Int, or Maybe (String, Bool), or so on.
Safer functions via Maybe



   Safer integer division:
   a ‘ s a f e D i v ‘ 0 = Nothing
   a ‘ s a f e D i v ‘ b = Just ( a ‘ div ‘ b )

   A safer version of head:
   safeHead [ ]            = Nothing
   s a f e H e a d ( x : ) = Just x
Exercise time!




   You should be familiar with the map function by now:
   map : : ( a −> b ) −> [ a ] −> [ b ]

   Write the equivalent function for the Maybe type:
   mapMaybe : : ( a −> b ) −> Maybe a −> Maybe b
Binary trees



   data Tree a = Empty
               | Node a ( Tree a ) ( Tree a )
                 d e r i v i n g ( Eq , Ord , Show)

   l e a f v = Node v Empty Empty

   someOldTree =
     Node ( l e a f ” f o o ” )
          ( Node ( l e a f ” b a r ” )
                    ( Node ( l e a f ” baz ” ) Empty ) )
Sizing a tree




   s i z e Empty = 0
   s i z e Node a b = 1 + s i z e a + s i z e b
Mapping again




  What should this function look like?
   mapTree : : ( a −> b ) −> Tree a −> Tree b
Generalising mapping

   So far, we’ve seen three different container types, with three
   different map-like functions:
   map      : : ( a −> b ) −> [ a ]   −> [ b ]
   mapMaybe : : ( a −> b ) −> Maybe a −> Maybe b
   mapTree : : ( a −> b ) −> Tree a −> Tree b

   It turns out we can write a typeclass to generalise this idea:
   c l a s s Functor f where
           fmap : : ( a −> b ) −> f a −> f b

   i n s t a n c e Functor Maybe where
           fmap = mapMaybe
Homework—binary search trees




   Turn the Tree type into a binary search tree by defining the
   following functions:
   i n s e r t : : ( Ord a ) = a −> Tree a −> Tree a
                                >
   c o n t a i n s : : ( Ord a ) = a −> Tree a −> Bool
                                  >
Homework—key/value containers

  Adapt your binary search tree code for use to create a simple
  key/value container:
   type Map a b       = Tree ( a , b )
   insertItem
      : : ( Ord a )   = a −> b −> Map a b −> Map a b
                       >
   lookupByKey
      : : ( Ord a )   = a −> Map a b −> Maybe b
                       >
   listToMap
      : : ( Ord a )   = [ ( a , b ) ] −> Map a b
                       >
   mapToList
      : : Map a b     −> [ ( a , b ) ]
   minItem
      : : ( Ord a )   = Map a b −> Maybe ( a , b )
                       >

Mais conteúdo relacionado

Mais procurados

Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
Johan Tibell
 

Mais procurados (20)

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 ...
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
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 - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
 
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
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generators
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
 

Destaque

Branding for a Cause
Branding for a CauseBranding for a Cause
Branding for a Cause
Jaci Russo
 
Surf Onderwijsdagen2008 Virtualisatie
Surf Onderwijsdagen2008 VirtualisatieSurf Onderwijsdagen2008 Virtualisatie
Surf Onderwijsdagen2008 Virtualisatie
Stichting Kennisnet
 
Getting to social roi
Getting to social roiGetting to social roi
Getting to social roi
Critical Mass
 
Kshitij Jewels Fashion Earrings
Kshitij Jewels Fashion EarringsKshitij Jewels Fashion Earrings
Kshitij Jewels Fashion Earrings
rachanasalvi
 

Destaque (20)

From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 
Branding for a Cause
Branding for a CauseBranding for a Cause
Branding for a Cause
 
Think before wasting food..
Think before wasting food..Think before wasting food..
Think before wasting food..
 
Escriptura humanistica
Escriptura humanisticaEscriptura humanistica
Escriptura humanistica
 
Современный инжиниринг. Особенности и тенденции.
Современный инжиниринг. Особенности и тенденции.Современный инжиниринг. Особенности и тенденции.
Современный инжиниринг. Особенности и тенденции.
 
How Planning Inspires Greatness
How Planning Inspires Greatness How Planning Inspires Greatness
How Planning Inspires Greatness
 
20110728 datalift-rpi-troy
20110728 datalift-rpi-troy20110728 datalift-rpi-troy
20110728 datalift-rpi-troy
 
Kryteria oceny relewantnosci - artykul - Ewa Bialek
Kryteria oceny relewantnosci - artykul - Ewa BialekKryteria oceny relewantnosci - artykul - Ewa Bialek
Kryteria oceny relewantnosci - artykul - Ewa Bialek
 
Web 2.0 Expo Presentation V4
Web 2.0 Expo Presentation V4Web 2.0 Expo Presentation V4
Web 2.0 Expo Presentation V4
 
Jozef Tischner
Jozef TischnerJozef Tischner
Jozef Tischner
 
Comparing US and Spanish student teachers' perceptions on Social Media
Comparing US and Spanish student teachers' perceptions on Social MediaComparing US and Spanish student teachers' perceptions on Social Media
Comparing US and Spanish student teachers' perceptions on Social Media
 
Iv'2012 brand map
Iv'2012 brand mapIv'2012 brand map
Iv'2012 brand map
 
Surf Onderwijsdagen2008 Virtualisatie
Surf Onderwijsdagen2008 VirtualisatieSurf Onderwijsdagen2008 Virtualisatie
Surf Onderwijsdagen2008 Virtualisatie
 
PCRS Ewa Bialek Biblioteka Slupsk
PCRS Ewa Bialek Biblioteka SlupskPCRS Ewa Bialek Biblioteka Slupsk
PCRS Ewa Bialek Biblioteka Slupsk
 
Planejamento de avaliação de experiências de aprendizagem com tecnologia
Planejamento de avaliação de experiências de aprendizagem com tecnologiaPlanejamento de avaliação de experiências de aprendizagem com tecnologia
Planejamento de avaliação de experiências de aprendizagem com tecnologia
 
Sharable notes
Sharable notesSharable notes
Sharable notes
 
E portafolis la nostra experiència a la uib, seu eivissa
E portafolis  la nostra experiència a la uib, seu eivissaE portafolis  la nostra experiència a la uib, seu eivissa
E portafolis la nostra experiència a la uib, seu eivissa
 
Getting to social roi
Getting to social roiGetting to social roi
Getting to social roi
 
Kshitij Jewels Fashion Earrings
Kshitij Jewels Fashion EarringsKshitij Jewels Fashion Earrings
Kshitij Jewels Fashion Earrings
 
Cvimc 2011 gebruik van ict door docenten in het MBO v1.0
Cvimc 2011 gebruik van ict door docenten in het MBO v1.0Cvimc 2011 gebruik van ict door docenten in het MBO v1.0
Cvimc 2011 gebruik van ict door docenten in het MBO v1.0
 

Semelhante a Real World Haskell: Lecture 5

Scala collections wizardry - Scalapeño
Scala collections wizardry - ScalapeñoScala collections wizardry - Scalapeño
Scala collections wizardry - Scalapeño
Sagie Davidovich
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
Devaraj Chilakala
 
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
agnesdcarey33086
 
Calculus - Functions Review
Calculus - Functions ReviewCalculus - Functions Review
Calculus - Functions Review
hassaanciit
 
Calculus 08 techniques_of_integration
Calculus 08 techniques_of_integrationCalculus 08 techniques_of_integration
Calculus 08 techniques_of_integration
tutulk
 
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
anhlodge
 

Semelhante a Real World Haskell: Lecture 5 (20)

List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 
Slope Fields For Snowy Days
Slope Fields For Snowy DaysSlope Fields For Snowy Days
Slope Fields For Snowy Days
 
5.3 dynamic programming 03
5.3 dynamic programming 035.3 dynamic programming 03
5.3 dynamic programming 03
 
Scala collections wizardry - Scalapeño
Scala collections wizardry - ScalapeñoScala collections wizardry - Scalapeño
Scala collections wizardry - Scalapeño
 
Assignments for class XII
Assignments for class XIIAssignments for class XII
Assignments for class XII
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
 
Polynomials and Curve Fitting in MATLAB
Polynomials and Curve Fitting in MATLABPolynomials and Curve Fitting in MATLAB
Polynomials and Curve Fitting in MATLAB
 
Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture g
 
Taylor problem
Taylor problemTaylor problem
Taylor problem
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
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
 
Monadologie
MonadologieMonadologie
Monadologie
 
Em01 ba
Em01 baEm01 ba
Em01 ba
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
 
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
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
Calculus - Functions Review
Calculus - Functions ReviewCalculus - Functions Review
Calculus - Functions Review
 
Calculus 08 techniques_of_integration
Calculus 08 techniques_of_integrationCalculus 08 techniques_of_integration
Calculus 08 techniques_of_integration
 
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
 

Mais de Bryan O'Sullivan (6)

Pronk like you mean it
Pronk like you mean itPronk like you mean it
Pronk like you mean it
 
CUFP 2009 Keynote - Real World Haskell
CUFP 2009 Keynote - Real World HaskellCUFP 2009 Keynote - Real World Haskell
CUFP 2009 Keynote - Real World Haskell
 
The other side of functional programming: Haskell for Erlang people
The other side of functional programming: Haskell for Erlang peopleThe other side of functional programming: Haskell for Erlang people
The other side of functional programming: Haskell for Erlang people
 
DEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellDEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World Haskell
 
Haskell for the Real World
Haskell for the Real WorldHaskell for the Real World
Haskell for the Real World
 
BayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore Haskell
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

Real World Haskell: Lecture 5

  • 1. Real World Haskell: Lecture 5 Bryan O’Sullivan 2009-11-04
  • 2. Adding quaternions We add two quaternions by adding their coefficients. a+ bi + cj + dk + w+ xi + yj + zk = (a + w ) + (b + x)i + (c + y )j + (d + z)k Or, in Haskell: addQ (Q a b c d ) (Q w x y z ) = Q ( a+w) ( b+x ) ( c+y ) ( d+z )
  • 3. Subtracting quaternions Subtraction is defined similarly. subQ (Q a b c d ) (Q w x y z ) = Q ( a−w) ( b−x ) ( c−y ) ( d−z )
  • 4. Typeclass inheritance The Eq typeclass that we met last week lets us compare values for equality. For many values, we want to be able to compare them for (total) ordering, for which we use the Ord typeclass. c l a s s ( Eq a ) = Ord a where > compare : : a −> a −> Ordering Notice the constraint on the Ord class: this states that in order for a type to be an instance of Ord, it must already be an instance of Eq.
  • 5. The Num typeclass Haskell defines a typeclass named Num that lets us express common arithmetic operations: c l a s s ( Eq a , Show a ) = Num a where > (+) : : a −> a −> a (∗) : : a −> a −> a (−) : : a −> a −> a negate : : a −> a abs : : a −> a {− e t c . −}
  • 6. Num and quaternions On first glance, we can easily fit our Quaternion type into the Num class. i n s t a n c e Num Q u a t e r n i o n where (+) = addQ (−) = subQ {− ??? −} We quickly run into problems: it’s not obvious what negate or abs should do. Maybe we can do something with multiplication, though?
  • 7. Multiplying quaternions If we can remember the identities i2 = j2 = k2 = ijk = −1 Then multiplication of quaternions falls out from the usual laws of arithmetic, but takes a complicated form: a + bi + cj + dk ∗ w + xi + y j + zk = aw − bx − cy − dz + (ax + bw + cz − dy )i + (ay − bz + cw + dx)j + (az + by − cx + dw )k
  • 8. Multiplying quaternions in Haskell It’s easy to convert our equation into executable form: mulQ (Q a b c d ) (Q w x y z ) = Q ( a ∗w − b∗ x − c ∗ y − d∗ z ) ( a ∗ x + b∗w + c ∗ z − d∗ y ) ( a ∗ y − b∗ z + c ∗w + d∗ x ) ( a ∗ z + b∗ y − c ∗ x + d∗w)
  • 9. Multiplying quaternions in Haskell It’s easy to convert our equation into executable form: mulQ (Q a b c d ) (Q w x y z ) = Q ( a ∗w − b∗ x − c ∗ y − d∗ z ) ( a ∗ x + b∗w + c ∗ z − d∗ y ) ( a ∗ y − b∗ z + c ∗w + d∗ x ) ( a ∗ z + b∗ y − c ∗ x + d∗w) Does this mean that we should augment our definition of Num as follows? i n s t a n c e Num Q u a t e r n i o n where ( ∗ ) = mulQ {− e t c . −}
  • 10. Arithmetic laws There are some laws that are so ingrained into our minds that we never think about them: m+n =n+m (commutative law of addition) (m + n) + k = m + (n + k) (associative law of addition) mn = nm (commutative law of multiplication) (mn)k = m(nk) (associative law of multiplication)
  • 11. Laws for quaternions We can see by simple inspection that addition over quaternions must satisfy the commutative and associative laws of normal arithmetic. We used those familiar arithmetic laws to derive the formula for quaternion multiplication, but do quaternions satisfy the commutative law of multiplication? Prelude> let a = Q 2 0 9 0 Prelude> let b = Q 0 9 0 2 Prelude> a ‘mulQ‘ b Q 0.0 36.0 0.0 (-77.0) Prelude> b ‘mulQ‘ a Q 0.0 0.0 0.0 85.0
  • 12. Laws: made to be broken? When you write or use a typeclass, there’s an implied understanding that you’ll obey its laws1 . Code that uses Eq relies on the fact that if a == b is True, then b == a will be True too, and a /= b will be False. Similarly, code that uses Num implicitly relies on the commutativity and associativity of addition and multiplication. 1 Unfortunately, these laws are often undocumented.
  • 13. Laws: made to be broken? When you write or use a typeclass, there’s an implied understanding that you’ll obey its laws1 . Code that uses Eq relies on the fact that if a == b is True, then b == a will be True too, and a /= b will be False. Similarly, code that uses Num implicitly relies on the commutativity and associativity of addition and multiplication. Neither the type system nor any other aspect of Haskell will help you to do the heavy lifting here: The burden is on you, the creator of a type, to ensure that if you make it an instance of a typeclass, that it follows the laws. 1 Unfortunately, these laws are often undocumented.
  • 14. A sketchy approach Since quaternion multiplication is not commutative, we should not implement (∗). But what more should we do? For instance, we could partially implement Num: i n s t a n c e Num Q u a t e r n i o n where (+) = addQ ( ∗ ) = undefined What effect does this have on code that tries to use multiplication? Prelude> scalar 2 * scalar 3 *** Exception: Prelude.undefined This is not very satisfactory behaviour.
  • 15. Playing fast and loose Of course, Haskell itself doesn’t escape the sin bin. What happens to those fancy laws in the presence of inexact arithmetic? Prelude> let a = 1e20 :: Double Prelude> (a + (-a)) + 1 1.0 Prelude> a + ((-a) + 1) 0.0 (This is the same behaviour as every other language that implements floating point, by the way.) A conclusion? You can violate the rules, but the compiler can’t remind you that you’re cheating.
  • 16. Code that might fail You’ve probably seen this behaviour by now: Prelude> 1 ‘div‘ 0 *** Exception: divide by zero These exceptions are often annoying, because we can’t easily catch and handle them. There exists a predefined type we can use to deal with these cases: data Maybe a = Nothing | Just a Notice that this type is parameterized, so we can have types such as Maybe Int, or Maybe (String, Bool), or so on.
  • 17. Safer functions via Maybe Safer integer division: a ‘ s a f e D i v ‘ 0 = Nothing a ‘ s a f e D i v ‘ b = Just ( a ‘ div ‘ b ) A safer version of head: safeHead [ ] = Nothing s a f e H e a d ( x : ) = Just x
  • 18. Exercise time! You should be familiar with the map function by now: map : : ( a −> b ) −> [ a ] −> [ b ] Write the equivalent function for the Maybe type: mapMaybe : : ( a −> b ) −> Maybe a −> Maybe b
  • 19. Binary trees data Tree a = Empty | Node a ( Tree a ) ( Tree a ) d e r i v i n g ( Eq , Ord , Show) l e a f v = Node v Empty Empty someOldTree = Node ( l e a f ” f o o ” ) ( Node ( l e a f ” b a r ” ) ( Node ( l e a f ” baz ” ) Empty ) )
  • 20. Sizing a tree s i z e Empty = 0 s i z e Node a b = 1 + s i z e a + s i z e b
  • 21. Mapping again What should this function look like? mapTree : : ( a −> b ) −> Tree a −> Tree b
  • 22. Generalising mapping So far, we’ve seen three different container types, with three different map-like functions: map : : ( a −> b ) −> [ a ] −> [ b ] mapMaybe : : ( a −> b ) −> Maybe a −> Maybe b mapTree : : ( a −> b ) −> Tree a −> Tree b It turns out we can write a typeclass to generalise this idea: c l a s s Functor f where fmap : : ( a −> b ) −> f a −> f b i n s t a n c e Functor Maybe where fmap = mapMaybe
  • 23. Homework—binary search trees Turn the Tree type into a binary search tree by defining the following functions: i n s e r t : : ( Ord a ) = a −> Tree a −> Tree a > c o n t a i n s : : ( Ord a ) = a −> Tree a −> Bool >
  • 24. Homework—key/value containers Adapt your binary search tree code for use to create a simple key/value container: type Map a b = Tree ( a , b ) insertItem : : ( Ord a ) = a −> b −> Map a b −> Map a b > lookupByKey : : ( Ord a ) = a −> Map a b −> Maybe b > listToMap : : ( Ord a ) = [ ( a , b ) ] −> Map a b > mapToList : : Map a b −> [ ( a , b ) ] minItem : : ( Ord a ) = Map a b −> Maybe ( a , b ) >