Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin Nullable型をモナドっぽくしてみた

Kotlin Nullable型をモナドっぽくしてみた

拡張関数を用いてNullable型を扱いやすくしてみました。

Taro Nagasawa

April 05, 2014
Tweet

More Decks by Taro Nagasawa

Other Decks in Programming

Transcript

  1. Optional static Optional<Integer> toInt(String str) {! ! // Integerʹม׵ͯ͠ฦ͢! }!

    ————————————————————————————————————————————————! Optional<String> a = getA();! Optional<Integer> b = ! a.flatMap(Sample::toInt);
  2. NotNull→Nullableͷؔ਺Λద༻Մ fun divide(a: Int, b: Int): Int?! ! ! !

    ! ! ! = if(b == 0) null else (a / b)! val partial = (::divide).curried()(100)! ! 2.nullable()?.bind(partial) // => 50! 0.nullable()?.bind(partial) // => null! null?.bind(partial) // => null
  3. NotNull→NotNullͷؔ਺Λద༻Մ fun square(i: Int): Int = i * i! !

    4.nullable()?.bind(::square) // => 16! null?.bind(::square) // => null
  4. if-else ΛഉআͰ͖ͨʂ // before! val b: Int? = if(a !=

    null) toInt(a) else null! ! // after! val b: Int? = a?.bind(::toInt)
  5. Nullableͳؔ਺͸μϝ fun next(i: Int) = i + 1! val nullableNext

    = ::next.nullable()! ! val a: Int? = 5! nullableNext?.invoke(a) // ܕ͕߹Θͳ͍! a?.bind(nullableNext) // ܕ͕߹Θͳ͍
  6. Nullableͳؔ਺΋ద༻Մ fun next(i: Int) = i + 1! val nullableNext

    = ::next.nullable()! ! val a: Int? = 5! a?.bind(nullableNext) // => 6! a?.bind(null) // => null
  7. Applicative Functor fun minus(a: Int, b: Int) = a –

    b! val minus = ::minus.curried()! ! val a: Int? = 5! val b: Int? = 3! b?.bind(a?.bind(minus)) // => 2