Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Last active October 12, 2015 22:08
Show Gist options
  • Select an option

  • Save j5ik2o/4093855 to your computer and use it in GitHub Desktop.

Select an option

Save j5ik2o/4093855 to your computer and use it in GitHub Desktop.
Option型(Maybeモナド)の自作
sealed trait MyOption[+A] {
def map[B](f: A => B): MyOption[B] =
if (isEmpty) MyNone else MySome(f(this.get))
def flatMap[B](f: A => MyOption[B]): MyOption[B] =
if (isEmpty) MyNone else f(this.get)
def get: A
def getOrElse[B >: A](elseValue: B):B =
if (isEmpty) elseValue else this.get
def isEmpty: Boolean
}
case class Some[A](private val value: A)
extends MyOption[A]{
def isEmpty = false
def get = value
}
case object None
extends MyOption[Nothing] {
def isEmpty = true
def get = throw new java.util.NoSuchElementException
}
object Main {
def testMatch(option: MyOption[Int]) {
val value = option match {
case MySome(v) => println("testMatch value = " + v)
case MyNone => ()
}
}
def testFlatMap(option: MyOption[Int]) {
val value = option.flatMap{ e =>
MyNone
}.getOrElse(0)
println("testFlatMap value = " + value)
}
def testMap(option: MyOption[Int]) {
val value = option.map{ e =>
e * 2
}.getOrElse(0)
println("testMap value = " + value)
}
def forTest(option: MyOption[MyOption[Int]]) {
val value = for{
a <- option
b <- a
} yield b
println("forTest = " + value.getOrElse(0))
}
def main(args : Array[String]) {
testMatch(MySome(2))
testFlatMap(MySome(1))
testMap(MySome(1))
forTest(MySome(MySome(1)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment