File tree Expand file tree Collapse file tree 5 files changed +76
-0
lines changed Expand file tree Collapse file tree 5 files changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ .idea /
2
+ target /
3
+ * .iml
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Simple functor example
3
+ */
4
+
5
+ case class Functor [A ](x : A ) {
6
+ def map [B ](f : (A ) => B ): Functor [B ] = Functor (f(x))
7
+ }
8
+
9
+ object Example {
10
+
11
+ def main (args : Array [String ]): Unit = {
12
+ val functor = Functor (2 )
13
+
14
+ println(" Functor rules" )
15
+
16
+ println(" 1. functor.map(x => x) = functor" )
17
+ println(s " functor.map(x => x) = ${functor.map(x => x)}" )
18
+ println(s " functor = $functor" )
19
+
20
+ println(" 2. functor.map(x => f(g(x))) = functor.map(g).map(f)" )
21
+ println(s " functor.map(x => f(g(x))) = ${functor.map(x => (x * 2 ) * 3 )}" )
22
+ println(s " functor.map(g).map(f) = ${functor.map(_ * 2 ).map(_ * 3 )}" )
23
+
24
+ }
25
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * NOT a functor because map method returns just value, not ValueMapper
3
+ */
4
+
5
+ case class ValueMapper [A ](x : A ) {
6
+ def map [B ](f : (A ) => B ): B =
7
+ f(x)
8
+ }
9
+
10
+ object NotFunctorExample {
11
+
12
+ def main (args : Array [String ]): Unit = {
13
+ val mapper = ValueMapper (" Hello" -> 123 )
14
+
15
+ println(mapper.map(_._1.toUpperCase))
16
+ }
17
+ }
Original file line number Diff line number Diff line change
1
+ case class Maybe [A ](x : Option [A ]) {
2
+ def map [B ](f : (A ) => B ): Maybe [B ] =
3
+ Maybe (x.map(f))
4
+
5
+ def isNothing = x.isEmpty
6
+
7
+ override def toString : String =
8
+ if (isNothing) " Maybe(Nothing)"
9
+ else s " Maybe( ${x.get}) "
10
+ }
11
+
12
+ object Maybe {
13
+ def apply [A ](x : A ): Maybe [A ] = Maybe (Some (x))
14
+
15
+ def empty [A ]: Maybe [A ] = Maybe [A ](None )
16
+ }
17
+
18
+ object ExampleMaybe {
19
+
20
+ def main (args : Array [String ]): Unit = {
21
+ val empty = Maybe .empty[Int ]
22
+ val notEmpty = Maybe (2 )
23
+
24
+ println(s " Expect Nothing, actual = ${empty.map(_ => 3 )}" )
25
+ println(s " Expect Maybe(3), actual = ${notEmpty.map(_ => 3 )}" )
26
+ }
27
+ }
Original file line number Diff line number Diff line change
1
+ ## Scala examples of Functor
2
+ Some great articles:
3
+ 1 . [ What is a functor?] ( https://medium.com/@dtinth/what-is-a-functor-dcf510b098b6 )
4
+ 2 . [ What's NOT a functor] ( https://medium.com/@dtinth/what-s-not-a-functor-57a081131555 )
You can’t perform that action at this time.
0 commit comments