Created
July 20, 2020 04:07
-
-
Save shomah4a/0f8cd88304f452570b4ef551ebfe6876 to your computer and use it in GitHub Desktop.
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
import arrow.core.Either | |
import arrow.core.extensions.fx | |
import arrow.core.flatMap | |
import java.lang.IllegalStateException | |
class Hello { | |
companion object { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val count = 100000 | |
println("count = $count") | |
for (i in 1..10) { | |
check("when", count) { | |
byWhen { somefunc() } | |
} | |
check("flatmap", count) { | |
byFlatMap { somefunc() } | |
} | |
check("fx", count) { | |
byFx { somefunc() } | |
} | |
} | |
} | |
} | |
} | |
fun check(msg: String, count: Int, f: () -> Unit) { | |
val start = System.currentTimeMillis() | |
for (i in 1 .. count) { | |
f() | |
} | |
val end = System.currentTimeMillis() | |
println("$msg: ${end-start} millisec") | |
} | |
fun byWhen(f: () -> Either<Exception, String>): Either<Exception, String> { | |
val a = f() | |
return when(val a = f()) { | |
is Either.Right -> { | |
when (val b = f()) { | |
is Either.Right -> | |
Either.Right(a.b + b.b) | |
else -> Either.Left(IllegalStateException("hoge")) | |
} | |
} | |
else -> Either.Left(IllegalStateException("fuga")) | |
} | |
} | |
fun byFlatMap(f: () -> Either<Exception, String>): Either<Exception, String> { | |
return f().flatMap { a -> | |
f().map { b -> | |
a + b | |
} | |
} | |
} | |
fun byFx(f: () -> Either<Exception, String>): Either<Exception, String> { | |
return Either.fx<Exception, String> { | |
val a = f().bind() | |
val b = f().bind() | |
a + b | |
} | |
} | |
fun somefunc(): Either<Exception, String> = | |
Either.Right("aiueo") | |
fun somefunc2(): Either<Exception, String> = | |
Either.Left(IllegalStateException("fuga")) |
Author
shomah4a
commented
Jul 20, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment