Skip to content

Commit efe29cc

Browse files
committed
Added Scala examples
1 parent 84be809 commit efe29cc

File tree

5 files changed

+76
-0
lines changed

5 files changed

+76
-0
lines changed

Scala/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.idea/
2+
target/
3+
*.iml

Scala/1-functor.scala

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

Scala/2-not-functor.scala

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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+
}

Scala/3-maybe.scala

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

Scala/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
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)

0 commit comments

Comments
 (0)