Skip to content

Commit aa8357c

Browse files
committed
optics
1 parent 1fa145b commit aa8357c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

constructive-programming/optics.sc

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//What could go wrong here?!/
2+
type Gender = Boolean
3+
type BirthDate = LocalDate
4+
5+
case class Person(name: String, birthDate: BirthDate, gender: Gender)
6+
case class Man(name: String, birthDate: BirthDate)
7+
8+
val personToMan: Person => Option[Man] = _ match {
9+
case Person(name, birthDate, True) => Some(Man(name, birthDate))
10+
case p => None
11+
12+
}
13+
14+
val manToPerson: Man => Person = m => Person(m.name, m.birthDate, True)
15+
16+
val getTime: IO[LocalDate] = ???
17+
18+
val personAge: Person => IO[Int] = p => getTime.map(p.birthDate.yearsBetween)
19+
20+
val manAge_1: Man => Option[IO[Int]] = ???
21+
val manAge_2: Man => IO[Int] = ???
22+
23+
case class Lens[S, A](get: S => A, set: A => S => S) {
24+
def modify(A => A): S => S = ???
25+
26+
def compose[T](other: Lens[T, S]): Lens[T, A] = ???
27+
28+
def choice[T](other: Lens[T, A]): Lens[S \/ T, A] = ???
29+
30+
def split[T, B](other: Lens[T, B]): Lens[S /\ T, A /\ B] = ???
31+
32+
}
33+
34+
//What could go wrong here?!/
35+
trait Functor[F[_]] {
36+
37+
def map[A, B](fa: F[A])(f: A => B): F[B] = ???
38+
39+
}
40+
41+
//What could go wrong here?!/
42+
case class Const[A, B](a: A) implicit def constFunctor[AA] = new
43+
Functor[Const[AA, ?]] {
44+
45+
def map[A, B](fa: Const[AA, A])(f: A => B): Const[AA, B] = ???
46+
47+
}
48+
49+
type TVL[S, A] = (Const[A, S], A => S) implicit def tvlFunctor[A] = new
50+
Functor[TVL[?, A]] {
51+
52+
def map[S, T](fa: TVL[S, A])(f: S => T): TVL[T, A] = ???
53+
54+
} trait Lens[S, A] {
55+
def apply[F[_]: Functor](A => F[A]): S => F[S]
56+
def get(s: S): A = ???
57+
def set(a: A, s: S): S = ???
58+
def modify(A => B): Lens[S, B] = ???
59+
def compose[T](other: Lens[T, S]): Lens[T, A] = ???
60+
def choice[T](other: Lens[T, A]): Lens[S \/ T, A] = ???
61+
def split[T, B](other: Lens[T, B]): Lens[S /\ T, A /\ B] = ???
62+
}

0 commit comments

Comments
 (0)