Last active
October 12, 2015 22:08
-
-
Save j5ik2o/4093855 to your computer and use it in GitHub Desktop.
Option型(Maybeモナド)の自作
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
| 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