-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path1-functor.scala
More file actions
49 lines (40 loc) · 1.28 KB
/
1-functor.scala
File metadata and controls
49 lines (40 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package functor
import scala.language.higherKinds
//Functor typeclass with existential F type
trait Functor[F[_]] {
def fmap[A, B](fa: F[A])(f: A => B): F[B]
}
object Functor {
//Summons functor instance if it is in scope
def apply[F[_]](implicit f: Functor[F]): Functor[F] = f
}
//Option typeclass that represents optional value. Value type is covariant
sealed trait Option[+A]
//Option child that holds value. Value type is covariant
case class Some[+A](get: A) extends Option[A]
//Option child that represents nothing
case object None extends Option[Nothing]
object Option {
//Some factory method
def some[T](value: T): Option[T] = Some(value)
//None factory method
def none[T]: Option[T] = None
/*
* Remember this factory methods and that
* their return type is Option and not Some or None,
* they will come in handy in second example ;)
*/
//Functor implementation for Option
implicit val optionFunctor: Functor[Option] = new Functor[Option] {
override def fmap[A, B](fa: Option[A])(f: A => B): Option[B] = fa match {
case Some(v) => Some(f(v))
case None => None
}
}
}
object Main1 extends App {
println(Functor[Option].fmap(None)((a: Int) => a + 2))
//prints None
println(Functor[Option].fmap(Some("2"))(_.toInt))
//prints Some(2)
}