Last active
August 9, 2019 00:08
-
-
Save bugarela/ff3cd27e1e7e70af2e2d13afc1e1aa9b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Compile with koltinc Either.kt | |
// Run with kotlin EitherKt | |
open class Either<A,B>{ | |
class Left<A, B>(val left: A) : Either<A,B>() | |
class Right<A, B>(val right: B) : Either<A,B>() | |
} | |
fun safeDiv(x:Int, y:Int) : Either<Unit, Int>{ | |
if (y == 0) return Either.Left(Unit) | |
return Either.Right(x / y) | |
} | |
open class Maybe<A> : Either<A,Unit>(){ | |
class Just<A>(val value: A) : Maybe<A>() | |
class Nothing<A>() : Maybe<A>() | |
} | |
fun safeDivMaybe(x:Int, y:Int) : Maybe<Int>{ | |
if (y == 0) return Maybe.Nothing() | |
return Maybe.Just(x / y) | |
} | |
// Prints with a Haskell-like syntax :D | |
fun <A,B> show(result: Either<A,B>): Unit = when(result) { | |
is Either.Left -> println("Left ${result.left}") | |
is Either.Right -> println("Right ${result.right}") | |
is Maybe.Just -> println("Just ${result.value}") | |
is Maybe.Nothing -> println("Nothing") | |
else -> println(result) | |
} | |
fun main(){ | |
show(safeDiv(3,0)) | |
show(safeDiv(6,1)) | |
show(safeDivMaybe(3,0)) | |
show(safeDivMaybe(6,1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment