Created
November 8, 2017 07:32
-
-
Save KimDaesap/df166ef5c9ac422480bfd0c565c80915 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://www.scala-exercises.org/cats/semigroup | |
*/ | |
import cats.implicits._ | |
import cats.kernel.Semigroup | |
Semigroup[Int].combine(1, 2) | |
Semigroup[List[Int]].combine(List(1, 2, 3), List(4, 5, 6)) | |
Semigroup[Option[Int]].combine(Option(1), Option(2)) | |
Semigroup[Option[Int]].combine(Option(1), None) | |
Semigroup[Int ⇒ Int].combine( | |
{ (x: Int) ⇒ x + 1}, | |
{ (x: Int) ⇒ x * 10}) | |
.apply(6) | |
Map("foo" -> Map("bar" -> 5)) | |
.combine(Map("foo" -> Map("bar" -> 6), "baz" -> Map())) | |
// = Map(foo -> Map(bar -> 11), baz -> Map()) | |
Map("foo" -> List(1, 2)) | |
.combine(Map("foo" -> List(3, 4), "bar" -> List(42))) | |
// = Map(foo -> List(1, 2, 3, 4), bar -> List(42)) | |
Map("foo" -> Map("bar" -> 5)) ++ | |
Map("foo" -> Map("bar" -> 6), "baz" -> Map()) | |
// = Map(foo -> Map(bar -> 6), baz -> Map()) | |
Map("foo" -> List(1, 2)) ++ | |
Map("foo" -> List(3, 4), "bar" -> List(42)) | |
// = Map(foo -> List(3, 4), bar -> List(42)) | |
val aMap = Map("foo" → Map("bar" → 5)) | |
val anotherMap = Map("foo" → Map("bar" → 6)) | |
val combinedMap = Semigroup[Map[String, Map[String, Int]]] | |
.combine(aMap, anotherMap) | |
// Map(foo -> Map(bar -> 11)) | |
combinedMap.get("foo") | |
val one: Option[Int] = Option(1) | |
val two: Option[Int] = Option(2) | |
val n: Option[Int] = None | |
one |+| two | |
n |+| two | |
n |+| n | |
two |+| n | |
/* | |
https://www.scala-exercises.org/cats/monoid | |
*/ | |
import cats.implicits._ | |
import cats.kernel.Monoid | |
Monoid[String].empty | |
Monoid[String].combineAll(List("a", "b", "c")) | |
Monoid[String].combineAll(List()) | |
Monoid[Map[String, Int]].combineAll(List(Map("a" → 1, "b" → 2), Map("a" → 3))) | |
Monoid[Map[String, Int]].combineAll(List()) | |
val l = List(1, 2, 3, 4, 5) | |
l.foldMap(identity) | |
l.foldMap(i ⇒ i.toString) | |
//implicit def monoidTuple[A: Monoid, B: Monoid]: Monoid[(A, B)] = | |
// new Monoid[(A, B)] { | |
// def combine(x: (A, B), y: (A, B)): (A, B) = { | |
// val (xa, xb) = x | |
// val (ya, yb) = y | |
// (Monoid[A].combine(xa, ya), Monoid[B].combine(xb, yb)) | |
// } | |
// def empty: (A, B) = (Monoid[A].empty, Monoid[B].empty) | |
// } | |
//val l = List(1, 2, 3, 4, 5) | |
l.foldMap(i ⇒ (i, i.toString)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment