Upcoming SlideShare
Loading in …5
×

# Introduction to Laws

4,923 views

Published on

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

Video: http://vimeo.com/58236838

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
Your message goes here
• Be the first to comment

No Downloads
Views
Total views
4,923
On SlideShare
0
From Embeds
0
Number of Embeds
46
Actions
Shares
0
Downloads
79
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
• Alternative title: Law &amp; 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

1. 1. Introduction to Laws
2. 2. About @nkpart Scalaz Functional JavaRuby/Scala/Haskell/Objective-C FunctionalKitMogeneration Kit Various ruby gems
3. 3. Why Laws?They are the footnote in everymonad tutorial.Too hard at the beginning.Programming isn’t even Mathsanyway.
4. 4. Laws are theNew/Old HotnessYou are already programming withLaws.Laws are fundamental tounderstanding most typeclasses.Programming *is* maths.
5. 5. What are Laws Understanding LawsLegal Benefits Breaking Laws
6. 6. What are Laws Common LawsLegal Benefits Breaking Laws
7. 7. (7 + 5) + 3 = 7 + (5 + 3)
8. 8. (a + b) + c = a + (b + c)
9. 9. (a ⊗ b) ⊗ c = a ⊗ (b ⊗ c)
10. 10. What are Laws?Laws are statements made aboutequivalence of expressions.Some Laws come from Maths Abstract Algebra
11. 11. 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!
12. 12. add :: Int -> Int -> Int
13. 13. What are Laws?Laws are not checked by the typesystemLaws can be broken byimplementationsVerification is usually done byhand Alternatively, QuickCheck.
14. 14. What are Laws?Statements of EquivalenceContracts for the ImplementorLaws are not checked by the typesystemOrigins in Maths. (Programming)
15. 15. What are Laws Common LawsLegal Benefits Breaking Laws
16. 16. Common LawsAbstract Algebra Associative Law Commutative Law IdentityTypeclasses and their Laws Monoid Functor
17. 17. Associative Law(a ⊗ b) ⊗ c = a ⊗ (b ⊗ c) Satisfied by: +, *, concat Uses: Parallelism. String building (refactoring)
18. 18. 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))))
19. 19. Commutativity Lawa ⊗ b = b ⊗ a Satisfied by: +, *, but not concat! Uses: Parallelism (again!)
20. 20. Commutative Law1 + (2 + ((3 + 4) + (5 + 6)))) apply the law!1 + (2 + ((5 + 6) + (3 + 4))))
21. 21. Identity Lawa ⊗ Id = a = Id ⊗ a Satisfied by: +/0, */1, concat/ []
22. 22. Typeclasses
23. 23. Monoidclass Monoid a where mappend :: a -> a -> a mempty :: a
24. 24. Monoidmappend satisfies theAssociative Lawmempty is the Identity for themappend operation.
25. 25. class Monoid a where mappend :: a -> a -> a mempty :: a
26. 26. MonoidCODE TIME
27. 27. Functor
28. 28. class Functor f where fmap :: (a -> b) -> f a -> f b
29. 29. Functor Lawsfmap id x = id xfmap (g . h) = (fmap g) . (fmap h)where id a = a id a = a
30. 30. Not a Functorinstance Functor [] where fmap f [] = [] fmap f (x:xs) = (f x):(f x):(fmap f xs)
31. 31. 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.
32. 32. What are Laws Common LawsLegal Benefits Breaking Laws
33. 33. Legal BenefitsMeaning to Multi-functionTypeclassesGreater understanding ofTypeclassesSubstitution of Expressions
34. 34. Instancing Functor CODE TIME
35. 35. Subsituting ExpressionsSome Haskell tooling can usethisHLintGHC Rewrite Rules
36. 36. HLintCODE TIME
37. 37. Rewrite Rules{-# RULES“map/map” forall f g xs.map f (map g xs) = map (f . g) xs#-}
38. 38. What are Laws Common LawsLegal Benefits Breaking Laws
39. 39. 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)
40. 40. “Lawless Typeclasses”class Zero a where zero :: aclass Pointed f where return :: a -> f a
41. 41. Broken Instances Broken typeclass instances exist Verification is hard. The Gen Monad: CODE TIME
42. 42. Consequences ofIllegal Behaviour
43. 43. Consequences ofIllegal Behaviour Bijection[Int, String]
44. 44. 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]?
45. 45. What are Laws Understanding LawsLegal Benefits Breaking Laws
46. 46. 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!
47. 47. Useful ResourcesHaskell Packages- Lens Typeclassopedia- Semigroupoids #scalaz- Pipes #haskell[.au] #bfpgScalaz
48. 48. Thanks!