Introduction to Laws
Upcoming SlideShare
Loading in...5
×
 

Introduction to Laws

on

  • 1,271 views

Talk given on 2013-01-22 to the BFPG: http://www.bfpg.org/events/87030712/

Talk given on 2013-01-22 to the BFPG: http://www.bfpg.org/events/87030712/

Video: http://vimeo.com/58236838

Statistics

Views

Total Views
1,271
Views on SlideShare
1,224
Embed Views
47

Actions

Likes
3
Downloads
15
Comments
0

2 Embeds 47

https://twitter.com 45
https://twimg0-a.akamaihd.net 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Alternative title: Law & Order: Refactoring Crime Unit.
  • We need to remember to come back to laws.
  • Understanding Laws: Explain a few fundamental laws, then learn some typeclasses by focussing on their laws.
  • 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
  • Generalised to Addition Made the integers parameters Only ‘+’ is left as an operator
  • Generalised statement about any binary operation Binary - takes 2 arguments, eg. plus, times, etc.
  • 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
  • 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.
  • Explain the signature: function name, syntax/puncutation, arguments, return type. Where does the law fit into this? It doesn’t.
  • 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.
  • 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.
  • 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.
  • Someone tell me a way of remembering this
  • Step from list to the operation Sum the list in any pairing of subsequent parts
  • Flipping. String addition, not satisfied. Prefix becomes suffix. + in java: commutative for integers, not commutative for strings. Should + be overloaded like this?
  • 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!
  • 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
  • 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.
  • 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?
  • 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.
  • Laws tie these functions together. Each could be implemented independently.
  • 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.
  • A step up from what we’re doing. Functor.
  • 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.
  • 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
  • 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
  • Laws tell us what a functor really is.
  • 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.
  • 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.
  • Verification is sometimes hard.
  • 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*.
  • Verification is sometimes hard.
  • 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.
  • 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.
  • 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.
  • Parallelism, optimisations
  • Lens is amazing. Look for his talk at NY Haskell. Pipes is a laws-driven implementation of iteratees.

Introduction to Laws Introduction to Laws Presentation Transcript

  • Introduction to Laws
  • About @nkpart Scalaz Functional JavaRuby/Scala/Haskell/Objective-C FunctionalKitMogeneration Kit Various ruby gems
  • Why Laws?They are the footnote in everymonad tutorial.Too hard at the beginning.Programming isn’t even Mathsanyway.
  • Laws are theNew/Old HotnessYou are already programming withLaws.Laws are fundamental tounderstanding most typeclasses.Programming *is* maths.
  • What are Laws Understanding LawsLegal Benefits Breaking Laws
  • What are Laws Common LawsLegal 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 aboutequivalence of expressions.Some Laws come from Maths Abstract Algebra
  • What are Laws?Integer addition obeys theAssociativity LawWherever we use IntegerAddition, we can use theproperties of the law to ouradvantage. 7 + 3 + 5 + 2 = 7 + (3 + 5) + 2For an implementor, the Law is aContract!
  • add :: Int -> Int -> Int
  • What are Laws?Laws are not checked by the typesystemLaws can be broken byimplementationsVerification is usually done byhand Alternatively, QuickCheck.
  • What are Laws?Statements of EquivalenceContracts for the ImplementorLaws are not checked by the typesystemOrigins in Maths. (Programming)
  • What are Laws Common LawsLegal Benefits Breaking Laws
  • Common LawsAbstract Algebra Associative Law Commutative Law IdentityTypeclasses 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/inject1 + (2 + (3 + (4 + (5 + 6)))) apply the law!1 + (2 + ((3 + 4) + (5 + 6))))
  • Commutativity Lawa ⊗ b = b ⊗ a Satisfied by: +, *, but not concat! Uses: Parallelism (again!)
  • Commutative Law1 + (2 + ((3 + 4) + (5 + 6)))) apply the law!1 + (2 + ((5 + 6) + (3 + 4))))
  • Identity Lawa ⊗ Id = a = Id ⊗ a Satisfied by: +/0, */1, concat/ []
  • Typeclasses
  • Monoidclass Monoid a where mappend :: a -> a -> a mempty :: a
  • Monoidmappend satisfies theAssociative Lawmempty is the Identity for themappend operation.
  • class Monoid a where mappend :: a -> a -> a mempty :: a
  • MonoidCODE TIME
  • Functor
  • class Functor f where fmap :: (a -> b) -> f a -> f b
  • Functor Lawsfmap id x = id xfmap (g . h) = (fmap g) . (fmap h)where id a = a id a = a
  • Not a Functorinstance Functor [] where fmap f [] = [] fmap f (x:xs) = (f x):(f x):(fmap f xs)
  • Functor LawsFunctor is a structure with an`fmap` that does not affect thatstructure, just the valuesinside.To modify the structure you needa different typeclass. The lawsprevent it.
  • What are Laws Common LawsLegal Benefits Breaking Laws
  • Legal BenefitsMeaning to Multi-functionTypeclassesGreater understanding ofTypeclassesSubstitution of Expressions
  • Instancing Functor CODE TIME
  • Subsituting ExpressionsSome Haskell tooling can usethisHLintGHC Rewrite Rules
  • HLintCODE TIME
  • Rewrite Rules{-# RULES“map/map” forall f g xs.map f (map g xs) = map (f . g) xs#-}
  • What are Laws Common LawsLegal Benefits Breaking Laws
  • Breaking LawsLawless 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 :: aclass Pointed f where return :: a -> f a
  • Broken Instances Broken typeclass instances exist Verification is hard. The Gen Monad: CODE TIME
  • Consequences ofIllegal Behaviour
  • Consequences ofIllegal Behaviour Bijection[Int, String]
  • Consequences ofIllegal 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 LawsLegal Benefits Breaking Laws
  • Laws are GoodLaws have a huge impact on the waywe code (already). Refactoring, Algebraic LawsTaking advantage of laws is apowerful programming technique. Understanding typeclasses, writing new instancesWatch out for Law breakers!
  • Useful ResourcesHaskell Packages- Lens Typeclassopedia- Semigroupoids #scalaz- Pipes #haskell[.au] #bfpgScalaz
  • Thanks!