Created
October 19, 2018 07:24
-
-
Save alwarren/7452b36b986beb32db5e4deab4de5541 to your computer and use it in GitHub Desktop.
A Kotlin Monad
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
/** | |
* Copyright (C) 2018 Fernando Cejas Open Source Project | |
* Modifications Copyright (C) 2018 Al Warren | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
/** | |
* Represents a value of one of two possible types (a disjoint union). | |
* Instances of [Either] are either an instance of [Left] or [Right]. | |
* FP Convention dictates that [Left] is used for "failure" | |
* and [Right] is used for "success". | |
* | |
* @see Left | |
* @see Right | |
*/ | |
sealed class Either<out L, out R> { | |
/** * Represents the left side of [Either] class which by convention is a "Failure". */ | |
data class Left<out L>(val a: L) : Either<L, Nothing>() { | |
val value: L get() = a // Modified to make value retrieval clearer | |
} | |
/** * Represents the right side of [Either] class which by convention is a "Success". */ | |
data class Right<out R>(val b: R) : Either<Nothing, R>() { | |
val value: R get() = b // Modified to make value retrieval clearer | |
} | |
val isRight get() = this is Right<R> | |
val isLeft get() = this is Left<L> | |
fun <L> left(a: L) = Left(a) | |
fun <R> right(b: R) = Right(b) | |
fun either(fnL: (L) -> Any, fnR: (R) -> Any): Any = | |
when (this) { | |
is Left -> fnL(a) | |
is Right -> fnR(b) | |
} | |
} | |
// Credits to Alex Hart -> https://proandroiddev.com/kotlins-nothing-type-946de7d464fb | |
// Composes 2 functions | |
fun <A, B, C> ((A) -> B).c(f: (B) -> C): (A) -> C = { | |
f(this(it)) | |
} | |
fun <T, L, R> Either<L, R>.flatMap(fn: (R) -> Either<L, T>): Either<L, T> = | |
when (this) { | |
is Either.Left -> Either.Left(a) | |
is Either.Right -> fn(b) | |
} | |
fun <T, L, R> Either<L, R>.map(fn: (R) -> (T)): Either<L, T> = this.flatMap(fn.c(::right)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment