Skip to content

Instantly share code, notes, and snippets.

@suzuki-hoge
Last active July 6, 2017 11:20
Show Gist options
  • Save suzuki-hoge/4ede3b7285ca6d9d0d8c5560d081559e to your computer and use it in GitHub Desktop.
Save suzuki-hoge/4ede3b7285ca6d9d0d8c5560d081559e to your computer and use it in GitHub Desktop.
  • JavaslangとかScalaRightProjectionみたいなのは省略
  • flatMapとかforとかapみたいなのも省略
  • extendsとかsuperも省略
  • 右優先とする
  • 両方ない、もしくは両方ある状態のEither<L, R>のインスタンスは生成出来ない様にせよ

以下のdefの部分はあえて情報量を減らしているが、Functionに明記する方がわかりやすいはず

def isEven = {
}
def toResultForInt = {
}
def toResultForError = {
}
Function<???, ???> isEven = {
}
Function<???, ???> toResultForInt = {
}
Function<???, ???> toResultForError = {
}

追加

  • String の数値を渡すと Integer に解析する関数を作成せよ
    • 0-9以外の文字を含む場合はparse errorを表す
    • 0 - 9の範囲外の数値(2桁と負数)の場合はrange errorを表す
    • それ以外の場合は Integer として返却
    • 戻りの型は後述
  • そのEitherの右側に+ 1を行う
  • 処理結果をResultTypeに変換する
    • 数値の場合はEVEN or ODD
    • 解析エラーの場合はPARSE_ERROR or RANGE_ERROR
  • 解析関数の戻りは以下のパターンを用意せよ
    • Either<String, Integer>
    • Either<ResultType, Integer>
class EitherTest extends Specification {
// テスト準備
Either<String, Integer> r = Either.right(5)
Either<String, Integer> l = Either.left('parse error')
enum ResultType {
EVEN, ODD, PARSE_ERROR, RANGE_ERROR
}
def isEven = {
it % 2 == 0
}
def toResultForInt = {
it % 2 == 0 ? EVEN : ODD
}
def toResultForError = {
it == 'parse error' ? PARSE_ERROR : RANGE_ERROR
}
// 以下テスト
def "get_on_right"() {
expect:
r.get() == 5
}
def "get_on_left"() {
when:
l.get()
then:
def exception = thrown(RuntimeException)
exception.message == 'this is not right!'
}
def "getOr_on_right"() {
expect:
r.getOr(3) == 5
}
def "getOr_on_left"() {
expect:
l.getOr(3) == 3
}
def "isRight_on_right"() {
expect:
r.isRight()
!r.isLeft()
}
def "isLeft_on_left"() {
expect:
!l.isRight()
l.isLeft()
}
def "map_on_right"() {
expect:
r.map(isEven) == Either.right(false)
}
def "map_on_left"() {
expect:
l.map(isEven).isLeft()
}
def "leftMap_on_right"() {
expect:
r.leftMap(toResultForError).isRight()
}
def "leftMap_on_left"() {
expect:
l.leftMap(toResultForError) == Either.left(PARSE_ERROR)
}
def "swap_on_right"() {
expect:
r.swap() == Either.left(5)
}
def "swap_on_left"() {
expect:
l.swap() == Either.right('parse error')
}
def "bimap_on_right"() {
expect:
r.bimap(toResultForError, isEven) == Either.right(false)
}
def "bimap_on_left"() {
expect:
l.bimap(toResultForError, isEven) == Either.left(PARSE_ERROR)
}
def "fold_on_right"() {
expect:
r.fold(toResultForError, toResultForInt) == ODD
}
def "fold_on_left"() {
expect:
l.fold(toResultForError, toResultForInt) == PARSE_ERROR
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment