group by reason of common characteris7c Type != Class Type Class == Class of Types Be aware of the seman.cs of the Class and Type here is based on Haskell but Scala
List[A]): A = ??? // A should be Int / String sum(List("a", "bc", "de")) // => "abcde" sum(List(1, 2, 3)) // => 6 sum(List(true, false)) // Kaboom! Can't compile Polymorphic behavior by instance type def sum[A](xs: List[A]): A = if (xs.isEmpty) A.unit else A.add(xs.head, sum(xs.tail)) Can it be done?
a -> a instance MyMonoid Int where add x y = x + y instance MyMonoid Double where add x y = x + y mySum :: (MyMonoid a) => a -> a -> a mySum x y = add x y main = do print $ mySum (1::Int) (2::Int) -- 3 print $ mySum (1::Double) (2::Double) -- 3.0 print $ mySum True False -- Kaboom! Can't compile
SemiGroup and Monoid abstract class SemiGroup[A] { def add(x: A, y: A): A } abstract class Monoid[A] extends SemiGroup[A] { def unit: A } 1 h$p:/ /lampwww.epfl.ch/~odersky/talks/wg2.8-boston06.pdf
works over arbitrary monoids def sum[A](xs : List[A])(m : Monoid[A]): A = if (xs.isEmpty) m.unit else m.add(xs.head, sum(xs.tail)(m)) One invokes this sum method by code such as sum(List("a", "bc", "de"))(stringMonoid) // => "abcde" sum(List(1, 2, 3))(intMonoid) // => 6 sum(List(true, false))(intMonoid) // => Can't compile definitely 1 h$p:/ /lampwww.epfl.ch/~odersky/talks/wg2.8-boston06.pdf
-> a -> a instance MyMonoid Int where add x y = x + y instance MyMonoid Double where add x y = x + y mySum :: (MyMonoid a) => a -> a -> a mySum x y = add x y main = do print $ mySum (1::Int) (2::Int) -- 3 print $ mySum (1::Double) (2::Double) -- 3.0 print $ mySum True False -- Kaboom! Can't compile
(Interface) with implementa5on at external of the type which is already exists • Sta)c Type Safe • Implicit parameter / defini5on binds to Type / Implement Not for laziness