Skip to content

Commit 0cd4cfc

Browse files
Kotlin step 2: Create typeclass Combinator
1 parent bde34ca commit 0cd4cfc

File tree

1 file changed

+42
-3
lines changed
  • kotlin/src/main/kotlin/com/fortyseven/fpfundamentals

1 file changed

+42
-3
lines changed

kotlin/src/main/kotlin/com/fortyseven/fpfundamentals/Contents.kt

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,55 @@
11
package com.fortyseven.fpfundamentals
22

3+
import arrow.extension
34
import arrow.higherkind
5+
import com.fortyseven.fpfundamentals.maybe.combinator.combinator
46

57
// Data types
68

79
@higherkind
810
sealed class Maybe<out A> : MaybeOf<A> {
11+
companion object {
12+
}
13+
914
data class Present<A>(val a: A) : Maybe<A>()
1015
object Absent : Maybe<Nothing>()
1116

12-
inline fun <B> fold(ifAbsent: () -> B, ifSome: (A) -> B): B = when (this) {
17+
inline fun <B> fold(ifAbsent: () -> B, ifPresent: (A) -> B): B = when (this) {
1318
is Absent -> ifAbsent()
14-
is Present<A> -> ifSome(a)
19+
is Present<A> -> ifPresent(a)
20+
}
21+
}
22+
23+
// Typeclasses
24+
25+
interface Combinator<A> {
26+
27+
fun combine(x: A, y: A): A
28+
}
29+
30+
// Instances
31+
32+
@extension
33+
interface IntCombinator : Combinator<Int> {
34+
override fun combine(x: Int, y: Int): Int = x + y
35+
}
36+
37+
fun Int.Companion.combinator(): Combinator<Int> =
38+
object : IntCombinator {}
39+
40+
@extension
41+
interface MaybeCombinator<A> : Combinator<Maybe<A>> {
42+
43+
fun CA(): Combinator<A>
44+
45+
override fun combine(x: Maybe<A>, y: Maybe<A>): Maybe<A> {
46+
return x.fold(
47+
{ y },
48+
{ xx ->
49+
y.fold(
50+
{ x },
51+
{ yy -> Maybe.Present(CA().combine(xx, yy)) })
52+
})
1553
}
1654
}
1755

@@ -24,7 +62,8 @@ class Program {
2462
fun getBalanceBank2(): Maybe<Int> = Maybe.Present(80)
2563

2664
val balance: Maybe<Int>
27-
get() = getBalanceBank1() + getBalanceBank2() // It won't compile
65+
get() = Maybe.combinator(Int.combinator())
66+
.combine(getBalanceBank1(), getBalanceBank2())
2867
}
2968

3069
fun main(args: Array<String>) {

0 commit comments

Comments
 (0)