SlideShare a Scribd company logo
Introduction to
      Laws
About @nkpart

                     Scalaz

                     Functional Java
Ruby/Scala/Haskell
/Objective-C         FunctionalKit

Mogeneration         Kit

                     Various ruby
                     gems
Why Laws?

They are the footnote in every
monad tutorial.

Too hard at the beginning.

Programming isn’t even Maths
anyway.
Laws are the
New/Old Hotness

You are already programming with
Laws.

Laws are fundamental to
understanding most typeclasses.

Programming *is* maths.
What are Laws    Understanding Laws




Legal Benefits     Breaking Laws
What are Laws     Common Laws




Legal Benefits   Breaking Laws
(7 + 5) + 3 = 7 +
     (5 + 3)
(a + b) + c =   a +
      (b + c)
(a ⊗ b) ⊗ c = a ⊗
     (b ⊗ c)
What are Laws?


Laws are statements made about
equivalence of expressions.

Some Laws come from Maths

 Abstract Algebra
What are Laws?
Integer addition obeys the
Associativity Law

Wherever we use Integer
Addition, we can use the
properties of the law to our
advantage.

 7 + 3 + 5 + 2 = 7 + (3 + 5) +
 2

For an implementor, the Law is a
Contract!
add :: Int -> Int
     -> Int
What are Laws?
Laws are not checked by the type
system

Laws can be broken by
implementations

Verification is usually done by
hand

 Alternatively, QuickCheck.
What are Laws?

Statements of Equivalence

Contracts for the Implementor

Laws are not checked by the type
system



Origins in Maths. (Programming)
What are Laws     Common Laws




Legal Benefits   Breaking Laws
Common Laws
Abstract Algebra

 Associative Law

 Commutative Law

 Identity

Typeclasses and their Laws

 Monoid

 Functor
Associative Law

(a ⊗ b) ⊗ c = a ⊗
     (b ⊗ c)
   Satisfied by: +, *, concat

   Uses: Parallelism. String
   building (refactoring)
Associative Law
    [1,2,3,4,5,6]
        fold/each/inject


1 + (2 + (3 + (4 + (5 +
         6))))
         apply the law!


1 + (2 + ((3 + 4) + (5
        + 6))))
Commutativity Law


a ⊗ b = b ⊗ a
 Satisfied by: +, *, but not
 concat!

 Uses: Parallelism (again!)
Commutative Law

1 + (2 + ((3 + 4) + (5
        + 6))))
        apply the law!


1 + (2 + ((5 + 6) + (3
        + 4))))
Identity Law

a ⊗ Id = a = Id ⊗
        a
  Satisfied by: +/0, */1, concat/
  []
Typeclasses
Monoid

class Monoid a where
 mappend :: a -> a -> a
 mempty :: a
Monoid

mappend satisfies the
Associative Law

mempty is the Identity for the
mappend operation.
class Monoid a where
 mappend :: a -> a -> a
 mempty :: a
Monoid


CODE TIME
Functor
class Functor f where
 fmap :: (a -> b) -> f a -> f b
Functor Laws

fmap id x = id x
fmap (g . h) =
  (fmap g) . (fmap h)

where
 id a = a
 id a = a
Not a Functor

instance Functor [] where
  fmap f [] = []
  fmap f (x:xs) = (f x):(f x):(fmap f xs)
Functor Laws

Functor is a structure with an
`fmap` that does not affect that
structure, just the values
inside.

To modify the structure you need
a different typeclass. The laws
prevent it.
What are Laws     Common Laws




Legal Benefits   Breaking Laws
Legal Benefits

Meaning to Multi-function
Typeclasses

Greater understanding of
Typeclasses

Substitution of Expressions
Instancing Functor



  CODE TIME
Subsituting
  Expressions

Some Haskell tooling can use
this

HLint

GHC Rewrite Rules
HLint



CODE TIME
Rewrite Rules

{-# RULES
“map/map” forall f g xs.
map f (map g xs) = map (f . g) xs
#-}
What are Laws     Common Laws




Legal Benefits   Breaking Laws
Breaking Laws
Lawless Typeclasses

 Pointed (Haskell
 [deprecated[ and Scalaz [never
 released])

 Zero (Scalaz [never released])

Real World Broken Instances

 Bijection (Twitter), ListT
 (Haskell Platform), Gen (from
 QuickCheck)
“Lawless
         Typeclasses”

class Zero a where
 zero :: a

class Pointed f where
 return :: a -> f a
Broken Instances


 Broken typeclass instances exist

 Verification is hard.

 The Gen Monad: CODE TIME
Consequences of
Illegal Behaviour
Consequences of
Illegal Behaviour



   Bijection[Int, String]
Consequences of
Illegal Behaviour
 Specific code using a
 Bijection[Int, String] might be
 fine.



 What if I write a function that
 uses a Bijection[A,B]?
What are Laws    Understanding Laws




Legal Benefits     Breaking Laws
Laws are Good
Laws have a huge impact on the way
we code (already).

 Refactoring, Algebraic Laws

Taking advantage of laws is a
powerful programming technique.

 Understanding typeclasses,
 writing new instances

Watch out for Law breakers!
Useful Resources

Haskell Packages

- Lens             Typeclassopedia

- Semigroupoids    #scalaz

- Pipes            #haskell[.au]

                   #bfpg

Scalaz
Thanks!

More Related Content

PPT
Project Lambda - Closures after all?
PPTX
A brief introduction to lisp language
PPTX
Prolog & lisp
PDF
Real World Haskell: Lecture 1
PDF
Learn a language : LISP
PPTX
Cs1123 9 strings
PPT
Haskell retrospective
Project Lambda - Closures after all?
A brief introduction to lisp language
Prolog & lisp
Real World Haskell: Lecture 1
Learn a language : LISP
Cs1123 9 strings
Haskell retrospective

What's hot (20)

PDF
DEFUN 2008 - Real World Haskell
PPSX
CS106 Lab 2 - Variables declaration
PPT
BayFP: Concurrent and Multicore Haskell
PDF
Monad as functor with pair of natural transformations
PPTX
Python The basics
PDF
Gentle Introduction To Lisp
ODP
Clojure basics
PDF
The Ring programming language version 1.6 book - Part 182 of 189
ODP
Functional Programming With Scala
PDF
Head First Java Chapter 8
PPT
INTRODUCTION TO LISP
PDF
Head First Java Chapter 4
PPTX
ODP
Introduction to Programming in LISP
PDF
LectureNotes-04-DSA
PPTX
LISP: Introduction to lisp
PPT
Advance LISP (Artificial Intelligence)
PDF
Python revision tour II
PPTX
C Theory
PPT
Lisp Programming Languge
DEFUN 2008 - Real World Haskell
CS106 Lab 2 - Variables declaration
BayFP: Concurrent and Multicore Haskell
Monad as functor with pair of natural transformations
Python The basics
Gentle Introduction To Lisp
Clojure basics
The Ring programming language version 1.6 book - Part 182 of 189
Functional Programming With Scala
Head First Java Chapter 8
INTRODUCTION TO LISP
Head First Java Chapter 4
Introduction to Programming in LISP
LectureNotes-04-DSA
LISP: Introduction to lisp
Advance LISP (Artificial Intelligence)
Python revision tour II
C Theory
Lisp Programming Languge
Ad

Viewers also liked (7)

PPTX
Intro to law notes
PPTX
Introduction to Law
PDF
Remedial law (2007 2013)
PDF
Mercantile law (2007 2013)
PDF
Labor law (2007 2013)
PDF
Political Law Bar Questions Guide
PPT
Defining Law
Intro to law notes
Introduction to Law
Remedial law (2007 2013)
Mercantile law (2007 2013)
Labor law (2007 2013)
Political Law Bar Questions Guide
Defining Law
Ad

Similar to Introduction to Laws (20)

PDF
Monad Laws Must be Checked
PDF
Introduction to ad-3.4, an automatic differentiation library in Haskell
PDF
Introduction to ad-3.4, an automatic differentiation library in Haskell
PPTX
GNAT Pro User Day: Ada 2012, Ravenscar and SPARK running on an Atmel ARM M4 (...
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
PDF
Practical cats
PPT
Stacksqueueslists
PPT
Stacks queues lists
PPT
Stacks queues lists
PPT
Stacks queues lists
PPT
Stack squeues lists
PPT
Stacks queues lists
PPTX
Introduction to Client-Side Javascript
PDF
Everything is composable
PDF
Programming in Scala - Lecture Four
PDF
Functional programming in C++
PPTX
C++11 - A Change in Style - v2.0
PDF
Orthogonal Functional Architecture
PDF
Google Interview Questions By Scholarhat
Monad Laws Must be Checked
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
GNAT Pro User Day: Ada 2012, Ravenscar and SPARK running on an Atmel ARM M4 (...
Столпы функционального программирования для адептов ООП, Николай Мозговой
Practical cats
Stacksqueueslists
Stacks queues lists
Stacks queues lists
Stacks queues lists
Stack squeues lists
Stacks queues lists
Introduction to Client-Side Javascript
Everything is composable
Programming in Scala - Lecture Four
Functional programming in C++
C++11 - A Change in Style - v2.0
Orthogonal Functional Architecture
Google Interview Questions By Scholarhat

More from nkpart (6)

KEY
Writing Better Haskell
KEY
Tools for writing Haskell programs
KEY
Tools for writing Haskell programs
KEY
Deriving Scalaz
KEY
Scala implicits
KEY
Taming Errors with FunctionalKit
Writing Better Haskell
Tools for writing Haskell programs
Tools for writing Haskell programs
Deriving Scalaz
Scala implicits
Taming Errors with FunctionalKit

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
cuic standard and advanced reporting.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Electronic commerce courselecture one. Pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation_ Review paper, used for researhc scholars
MYSQL Presentation for SQL database connectivity
Reach Out and Touch Someone: Haptics and Empathic Computing
cuic standard and advanced reporting.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Machine learning based COVID-19 study performance prediction
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
20250228 LYD VKU AI Blended-Learning.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Empathic Computing: Creating Shared Understanding
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Electronic commerce courselecture one. Pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25 Week I

Introduction to Laws

Editor's Notes

  • #2: Alternative title: Law & Order: Refactoring Crime Unit.
  • #4: We need to remember to come back to laws.
  • #6: Understanding Laws: Explain a few fundamental laws, then learn some typeclasses by focussing on their laws.
  • #8: Familiarity from School Example of the use of a law. What’s it name? Note some similarities to programming: * Expressions on the left hand side and right hand side * Substitutability
  • #9: Generalised to Addition Made the integers parameters Only ‘+’ is left as an operator
  • #10: Generalised statement about any binary operation Binary - takes 2 arguments, eg. plus, times, etc.
  • #11: We’ve now seen an example of a law, and where it came from We’ve seen an example of a function satisfying a law
  • #12: We can leverage the law in programming: doing the operations in order that is most clear to readers, or fastest. If you’re writing a function, and you’re calling it integer addition, you need to satisfy the law. Or you will be taken down. The law is just like programming with contracts.
  • #13: Explain the signature: function name, syntax/puncutation, arguments, return type. Where does the law fit into this? It doesn’t.
  • #14: Technique for hand verification is equational reasoning, see that later Occasionally verified with QuickCheck, but it’s hard to satisfy yourself. QuickCheck requires a good Arbitrary. Easy to get wrong.
  • #15: Statements of equivalence? Refactoring! Substituting methods for expressions, expressions for expressions, etc. Contracts in programming (not null parameters, etc.) are very useful. When a new law is required, the decision is made by the community. The most useful law is generally obvious.
  • #17: Tackle in 2 parts. First we’ll look at some laws that may be familiar. The ones from abstract algebra, that apply to things like addition and multiplication. Second part we’ll look at some typeclasses, and the laws they require. Generalising part 1.
  • #18: Someone tell me a way of remembering this
  • #19: Step from list to the operation Sum the list in any pairing of subsequent parts
  • #20: Flipping. String addition, not satisfied. Prefix becomes suffix. + in java: commutative for integers, not commutative for strings. Should + be overloaded like this?
  • #21: Start with our application of the associative law. Commutative law says we can swap all the parts Now, if we parallelise this operation as summing into an accumulator, it now longer matters which parts of our computation come out first. Because Laws! How useful!
  • #22: This is interesting, because there are now 2 parts. The identity value, and a binary operation. There’s a relationship here between two things. TODO: show a + 0, a * 1, matrix * I
  • #23: Now to typeclasses, which is where things get real. Now I want to build on what we’ve just seen. Particularly, Associativity (changing the parentheses), and Identity.
  • #24: Explain the code. This is an interface. Note there’s something missing. We have 2 functions we need to implement, but nothing about how they should be implemented yet. Also, there’s nothing that ties these 2 functions together. At this point we know where this is going. Anyone want to take a stab?
  • #25: This is interesting, because there are now 2 parts. The identity value, and a binary operation. There’s a relationship here between two things. Relationship is what is important. Jump back.
  • #26: Laws tie these functions together. Each could be implemented independently.
  • #27: This is interesting, because there are now 2 parts. The identity value, and a binary operation. There’s a relationship here between two things. Relationship is what is important. Jump back.
  • #28: A step up from what we’re doing. Functor.
  • #29: Explain the code again. What is a functor? something you can map over. Anything with a map function. Transforming contents of a containing is one of the most obvious implementations.
  • #30: Explain each law on its own. Space is function application. Show that they are statements of equivalence. Meaning: * does not change the structure * changes a value without changing its context
  • #31: Duplicates the first functor value. If we do fmap with identity, we’ll end up with an extra value out the front. This is not the same as just doing identity. We’ll see how to implement a real one soon
  • #32: Laws tell us what a functor really is.
  • #34: understanding Monoid: Identity means nothing without an Mappend. Defined in terms of mappend. understanding fmap: preserving the structure. We can use that to help us define instances. Substitution: Tooling can take advantage of this.
  • #38: This is not a law. This is a rewrite statement in GHC. Specific to lists, however it could be (because of laws) changed to fmap. Then it looks very similar to the statement of the fmap for composition.
  • #40: Verification is sometimes hard.
  • #41: Splitting apart Monoid and Monad. What can we say about these functions? What laws can we write? Nothing. They both require other functions to define themselves *meaningfully*.
  • #42: Verification is sometimes hard.
  • #43: A bijection: Everything in X maps to EXACTLY one item in Y. Every X is covered. Every Y is covered. There must be an inverse.
  • #44: Every Int must map to a unique String, *every* string must map to a unique integer. Otherwise this is not a bijection. Trivial to prove its not the case.
  • #45: Every Int must map to a unique String, *every* string must map to a unique integer. Otherwise this is not a bijection. Trivial to prove its not the case.
  • #47: Parallelism, optimisations
  • #48: Lens is amazing. Look for his talk at NY Haskell. Pipes is a laws-driven implementation of iteratees.