Skip to content

Instantly share code, notes, and snippets.

@ngsw-taro
Last active January 7, 2016 02:53
Show Gist options
  • Save ngsw-taro/b20d303dd0da4916ccf9 to your computer and use it in GitHub Desktop.
Save ngsw-taro/b20d303dd0da4916ccf9 to your computer and use it in GitHub Desktop.
Type class in Kotlin (failed)
import Option.None
import Option.Some
interface Type<out A, out B: Type<A, B>>
sealed class Option<out A>: Type<A, Option<A>> {
object None: Option<Nothing>() {
override fun toString(): String = "None"
}
data class Some<A>(val value: A): Option<A>()
}
interface Functor<A, B, F: Type<A, F>, G: Type<B, G>> {
fun map(a: F, f: (A) -> B): G
}
fun <A, B> optionFunctor() = object: Functor<A, B, Option<A>, Option<B>> {
override fun map(a: Option<A>, f: (A) -> B): Option<B> =
when (a) {
is Some<A> -> Some(f(a.value))
is None -> None
}
}
// 補助用
fun <A, B> Option<A>.map(f: (A) -> B): Option<B> = optionFunctor<A, B>().map(this, f)
fun main(args: Array<String>) {
val a: Option<Int> = optionFunctor<Int, Int>().map(Some(5), { it * 2 })
println(a) //=> Some(value=10)
val b: Option<Int> = optionFunctor<Int, Int>().map(None, { it * 2 })
println(b) //=> None
val c: Option<Int> = Some("123") map { it.toInt() }
println(c) //=> Some(value=123)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment