Skip to content

Instantly share code, notes, and snippets.

@bugarela
Last active August 9, 2019 00:08
Show Gist options
  • Save bugarela/ff3cd27e1e7e70af2e2d13afc1e1aa9b to your computer and use it in GitHub Desktop.
Save bugarela/ff3cd27e1e7e70af2e2d13afc1e1aa9b to your computer and use it in GitHub Desktop.
// 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