Last active
July 29, 2016 15:11
-
-
Save takaki/4a0be13a5d2b11a10f8c450ba743f451 to your computer and use it in GitHub Desktop.
joinRight・joinLeftを入れ子ifの替わりに使う ref: http://qiita.com/takaki@github/items/5dba09ff6016cec367f2
This file contains 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
package example | |
object EitherDemo { | |
def main(args: Array[String]) { | |
println(oddAndPositive(-1)) | |
println(oddAndPositive(0)) | |
println(oddAndPositive(1)) | |
println(oddAndPositive2(-1)) | |
println(oddAndPositive2(0)) | |
println(oddAndPositive2(1)) | |
println(oddOrPositive(-2)) | |
println(oddOrPositive(-1)) | |
println(oddOrPositive(0)) | |
println(oddOrPositive2(-2)) | |
println(oddOrPositive2(-1)) | |
println(oddOrPositive2(0)) | |
} | |
def mod(i: Int, j: Int) = (i % j + j) % j | |
def oddOrPositive(i: Int): Either[String, Int] = { | |
Either.cond(i >= 0, i, Either.cond(mod(i, 2) == 1, i, "even and negative number")).joinLeft | |
} | |
def oddOrPositive2(i: Int): Either[String, Int] = { | |
if (i >= 0) { | |
Right(i) | |
} else if (mod(i, 2) == 1) { | |
Right(i)a | |
} else { | |
Left("even and negative number") | |
} | |
} | |
def oddAndPositive(i: Int): Either[String, Int] = { | |
Either.cond(i >= 0, Either.cond(mod(i, 2) == 1, i, "even number"), "negative number").joinRight | |
} | |
def oddAndPositive2(i: Int): Either[String, Int] = { | |
if (i >= 0) { | |
if (mod(i, 2) == 1) { | |
Right(i) | |
} else { | |
Left("even number") | |
} | |
} else { | |
Left("negative number") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment