polimorfismo cosa?
TRANSCRIPT
Settembre 2015
@filippovitale
Polimorfismo parametrico, polimorfismo su misura e
polimorfismo cosa?
3 sempliciData Structure
Seq Set Map
package scala.collection
Seq Set Map
package scala.collection
v v v v
Seq Set Map
package scala.collection
valueAvalueB
valueC
Seq Set Map
package scala.collection
key value
key value
key value
Seq Set Map
package scala.collection
base trait per implementazioni mutable e immutable
package scala.collection
Seq Set Map
package scala.collection.mutable
ArrayBuffer HashSet HashMap
package scala.collection.mutable
ArrayBuffer HashSet HashMap
“Mutability is an optimisation – perhaps premature”
package scala.collection
Seq Set
package scala.collection.immutable
Map
List HashSet HashMap
package scala.collection.mutable
ArrayBuffer HashSet HashMap
http://docs.scala-lang.org/tutorials/FAQ/collections.html
package scala.collection.immutable
List HashSet HashMap
Immutabilità implica:- equational reasoning- sharing with referential integrity- thread safety- …
“When you get used to immutable data, ya kinda forget how to use mutable data in a sensible way.” – Jessica Kerr
package scala.collection
Traversable
Seq Set Map
Quali metodi offreTraversable?
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
isEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Metodi offerti da Traversabledef map[B](f: A => B)
isEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Metodi offerti da Traversable
def foreach(f: (A) => Unit): Unit
def map[B](f: A => B)
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
isEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Metodi offerti da Traversabledef foldLeft[B](z: B)(f: (B, A) => B): B
isEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Metodi offerti da Traversabledef foldLeft[B](z: B)(f: (B, A) => B): B
def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)
isEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Metodi offerti da Traversabledef foldLeft[B](z: B)(f: (B, A) => B): B
def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)
Theorems for free! – http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf
Parametricity – http://yowconference.com.au/slides/yowlambdajam2014/Morris-ParametricityTypesAreDocumentation.pdf
Unire Strutture Dati
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
def ++[B](that: Traversable[B]): Traversable[B]
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
def ++[B](that: Traversable[B]): Traversable[B]
Traversable Seq List
List(1, 2, 3) ++ List(4, 5, 6) == ???
List(1, 2, 3) ++ List(4, 5, 6) == List(1, 2, 3, 4, 5, 6)
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
def ++[B](that: Traversable[B]): Traversable[B]
Traversable Set HashSet
Set(1, 2, 3) ++ Set(4, 5, 6) == ???
Set(1, 2, 3) ++ Set(4, 5, 6) == Set(5, 1, 6, 2, 3, 4)
Set(1, 2, 3) ++ Set(4, 5, 6) == Set(5, 1, 6, 2, 3, 4)
Set(1, 2) ++ Set(2, 3) == Set(1, 2, 3)
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
def ++[B](that: Traversable[B]): Traversable[B]
Traversable Map HashMap
Map("a" -> 1) ++ Map("b" -> 2) == Map("a" -> 1, "b" -> 2)
E in casi più complessi?
Map[String, Set[Int]]
Map[String, Set[Int]]
“a” Set(1, 2)
“key b” Set(4, 7, 5)
“key c” Set(9, 4)
“a” Set(2, 3)
“key c” Set(3, 4)
“key d” Set(5, 6)
Map("a" -> Set(1, 2)) ++ Map("a" -> Set(2, 3)) == ???
Map("a" -> Set(1, 2)) ++ Map("a" -> Set(2, 3)) == ???
1: Map("a" -> Set(1, 2))
2: Map("a" -> Set(1, 2, 3))
3: Map("a" -> Set(2, 3))
4: RuntimeException
5: Compiler Error
Map("a" -> Set(1, 2)) ++ Map("a" -> Set(2, 3)) == ???
1:
2:
3: Map("a" -> Set(2, 3))
4:
5:
Map("a" -> Set(1, 2)) ??? Map("a" -> Set(2, 3))
Map("a" -> Set(1, 2, 3))
Metodi offerti da TraversableisEmptysizehasDefiniteSize++mapflatMapfilterremovepartitiongroupByforeach
reduceRightOptheadheadOptiontaillastlastOptioninittakedropslicetakeWhile
forallexistscountfindfoldLeft/:foldRight:\reduceLeftreduceLeftOptreduceRight
dropWhilespansplitAttoArraytoListtoIterabletoSeqtoStreamsortWithmkStringtoString
Seq Set Map✔ ✔ ✘
Quando vuoi un lavoro fatto bene…
“a” Set(1, 2) “a” Set(2, 3)
“a” Set(1, 2) ++ Set(2, 3)
“a” Set(1, 2) “a” Set(2, 3)
“a” Set(1, 2, 3)
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]]
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]] = { mb foreach { case (k, v) => ??? } }
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]] = { val result = mutable.Map() ++ ma mb foreach { case (k, v) => ??? } result.toMap}
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]] = { val result = mutable.Map() ++ ma mb foreach { case (k, v) => if (result.contains(k)) result += k -> (result(k) ++ v) else result += k -> v } result.toMap}
Implementazionecon Map immutable
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]] = {
}
(ma /: mb) { case (result,(k, v)) => if (result.contains(k)) result + (k -> (result(k) ++ v)) else result + (k -> v)}
val result = mutable.Map() ++ mamb foreach { case (k, v) => if (result.contains(k)) result += k -> (result(k) ++ v) else result += k -> v}result.toMap
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]] = { (ma /: mb) { case (result,(k, v)) => if (result.contains(k)) result + (k -> (result(k) ++ v)) else result + (k -> v) }}
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v }}
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v } // .map(_ ++ v).getOrElse(v)
}}
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v } // .map(_ ++ v).getOrElse(v) // .some(_ ++ v).none(v)
}}
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v } // .map(_ ++ v).getOrElse(v) // .some(_ ++ v).none(v) // .fold(v)(_ ++ v)
}}
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v } // .map(_ ++ v).getOrElse(v) // .some(_ ++ v).none(v) // .fold(v)(_ ++ v) // .cata(_ ++ v, v)}}
“FP with Bananas, Lenses, Envelopes and Barbed Wire” – http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.125http://en.wikipedia.org/wiki/Catamorphism
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v } // .map(_ ++ v).getOrElse(v) // .some(_ ++ v).none(v) // .fold(v)(_ ++ v) // .cata(_ ++ v, v)}}
http://stackoverflow.com/questions/5328007/why-doesnt-option-have-a-fold-method
(ma /: mb) { case (result,(k, v)) =>result + (k -> { result.get(k) match { case Some(vr) => vr ++ v case None => v } // .map(_ ++ v).getOrElse(v) // .some(_ ++ v).none(v) // .fold(v)(_ ++ v) // .cata(_ ++ v, v)}}
http://stackoverflow.com/questions/5328007/why-doesnt-option-have-a-fold-method
(ma /: mb) { case (result, (k, v)) => result + (k -> result.get(k).cata(_ ++ v, v))}
mb foreach { case (k, v) => result += (k -> result.get(k).cata(_ ++ v, v))}
(ma /: mb) { case (result, (k, v)) => result + (k -> result.get(k).cata(_ ++ v, v))}
mb foreach { case (k, v) => result += (k -> result.get(k).cata(_ ++ v, v))}
E se volessimo unire due mappe con type diversi?
Map[String, Set[Int]] Map[String, Map[Int, Set[Int]]]
Map[String, Set[Int]] Map[String, Map[Int, Set[Int]]]
def blend(ma: Map[String, Set[Int]], mb: Map[String, Set[Int]]): Map[String, Set[Int]] = ???
def blend(ma: Map[String, Map[Int, Set[Int]]], mb: Map[String, Map[Int, Set[Int]]]): Map[String, Map[Int, Set[Int]]] = ???
Map[String, Set[Int]] Map[String, Map[Int, Set[Int]]]
(ma /: mb) { case (result, (k, v)) => result + (k -> result.get(k).cata(_ ++ v, v)) }
(ma /: mb) { case (result, (k, v)) => result + ??? // { ??? => { ??? } } }
Map[String, Set[Int]] Map[String, Map[Int, Set[Int]]]
trait Blendable[A] { def blend(ma: A, mb: A): A}
Map[String, Set[Int]] Map[String, Map[Int, Set[Int]]]
trait Blendable[A] { def blend(ma: A, mb: A): A}
new Blendable[...] { def blend(ma: ..., mb: ...): ... = ???}
Map[String, Set[Int]] Map[String, Map[Int, Set[Int]]]
trait Blendable[A] { def blend(ma: A, mb: A): A}
new Blendable[...] { def blend(ma: ..., mb: ...): ... = ???}x10 Developer
Cosa intendiamo veramente per “blend”
List utilizzando l’operatore binario ++
Set utilizzando l’operatore binario ++
List(1, 2, 3) ++ List(4, 5, 6) == List(1, 2, 3, 4, 5, 6)
Set(1, 2) ++ Set(2, 3) == Set(1, 2, 3)
(List, ++)(Set, ++)
(1 blend 2) == ???
(List, ++)(Set, ++)
(Int, +)
(1 blend 2) == 1 + 2 == 3
(List, ++)(Set, ++)
(Int, +)(String, +)("ab" blend "cd") == ("ab" + "cd") == "abcd"
(List, ++)(Set, ++)
(Int, +)(String, +)
(Map[...], Blendable[...].blend)
Blendable[Map[String, Set[Int]]].blend(ma, mb)
Cosa potrebbe consigliarci un Matematico?
WARNING
Algebra ahead
☣
https://it.wikipedia.org/wiki/Semigruppo
“Un semigruppo è un insieme S munito di una operazione binaria associativa m: S × S → S”
https://it.wikipedia.org/wiki/Propriet%C3%A0_di_chiusura
Proprietà di chiusura ≝ ∀a, b ∈ T : a∙b ∈ T
Per ogni a, b in T, il risultato dell’operazione a⋅b è in T:
trait Semigroup[T] { def op(a: T, b: T): T}
def op(a: Boolean, b: Boolean): Boolean
def op(a: Int, b: Int): Boolean
✓
✘
https://it.wikipedia.org/wiki/Associativit%C3%A0
Legge Associativa ≝ ∀a, b, c ∈ T : (a∙b)∙c = a∙(b∙c)
Ogni a, b e c in T soddisfano (a∙b)∙c = a∙(b∙c)
trait Semigroup[T] { def op(a: T, b: T): T}
((a op b) op c) == (a op (b op c))
https://it.wikipedia.org/wiki/Semigruppo
“Un semigruppo è un insieme S munito di una operazione binaria associativa m: S × S → S”
Scalaz e Semigruppi
import scalaz.std.set._
implicit def setSemigroup[A]:Semigroup[Set[A]] = new Semigroup[Set[A]] { def append(f1: Set[A], f2: => Set[A]) = f1 ++ f2 }
implicit def setSemigroup[A]:Semigroup[Set[A]] = new Semigroup[Set[A]] { def append(f1: Set[A], f2: => Set[A]) = f1 ++ f2 }
op
import scalaz.syntax.semigroup._import scalaz.std.list._
List(1, 2) |+| List(3, 4)
res: List[Int] = List(1, 2, 3, 4)
import scalaz.syntax.semigroup._import scalaz.std.set._
Set(1, 2) |+| Set(2, 3)
res: Set[Int] = Set(1, 2, 3)
import scalaz.syntax.semigroup._import scalaz.std.anyVal._
1 |+| 2 |+| 3
res: Int = 6
import scalaz.syntax.semigroup._import scalaz.std.string._
"a" |+| "b" |+| "c"
res: String = "abc"
/*** A semigroup in type F must satisfy two laws: * * - '''closure''': `∀ a, b in F, append(a, b)` is also in `F`. * - '''associativity''': `∀ a, b, c` in `F`, the equation * `append(append(a, b), c) = append(a, append(b , c))` holds.*/trait SemigroupLaw { def associative(f1: F, f2: F, f3: F)(implicit F: Equal[F]): Boolean = F.equal(append(f1, append(f2, f3)), append(append(f1, f2), f3))}
import scalaz.scalacheck.ScalazProperties._import scalaz.std.anyVal._
semigroup.laws[Int].check
+ semigroup.associative: OK, passed 100 tests.
semigroup.laws[String].checksemigroup.laws[Set[Int]].checksemigroup.laws[List[String]].checksemigroup.laws[Map[Int, Int]].check
+ semigroup.associative: OK, passed 100 tests.+ semigroup.associative: OK, passed 100 tests.+ semigroup.associative: OK, passed 100 tests.+ semigroup.associative: OK, passed 100 tests.
La nostra Map[_, Set[Int]]è un semigruppo?
Map("a" -> 1, "b" -> 4) |+| Map("a" -> 2)
res: Map[…] = Map(a -> 3, b -> 4)
“Some data structures form interesting semigroups as long as the types of the elements they contain also form semigroups.”
import scalaz.scalacheck.ScalazProperties._
semigroup.laws[Map[String, Set[Int]]].check
+ semigroup.associative: OK, passed 100 tests. ✓
Map("a" -> Set(1, 2)) |+| Map("a" -> Set(2, 3))
res: Map[…] = Map(a -> Set(1, 2, 3))
“adattato” da: Functional Programming in Scala - Part 3 - Chapter 10 Monoids
✓
Ma nel mio codebasenon ho Map così semplici…
Map("a" -> Map("aa" -> Map("aaa" -> Map("aaaa" -> List(1, 3), "aaab" -> List(2, 4))))) |+| Map("a" -> Map("aa" -> Map("aaa" -> Map("aaaa" -> List(5, 7), "aaab" -> List(6, 8)))))
Map(a->Map(aa->Map(aaa->Map(aaaa->List(1, 3, 5, 7), aaab->List(2, 4, 6, 8)))))
Benchmarking
“Experience indicates that nearly everybody has the wrong idea about the real bottlenecks
in his programs” – Donald Knuth
Computer programming as an art (1974) – http://dl.acm.org/citation.cfm?id=361612
Map[String, Set[Int]]
Settembre 2015
@filippovitale
$ tail -f domande