ピエールの綱渡りとは、
ピエールがバランス棒を持って綱渡りしている最中、バランス棒の左右に鳥がとまる。左右の鳥の数の差が3より大きくなったらピエールは落下して綱渡りが失敗する。左右の鳥の数の差が3以下のままで最後までいけたら成功。
という、すごいH本に出てくるやつです。これが独習ScalaZに出てくるので、なんぞやという感じでしたので。
Haskellで書くとこう。
type Birds = Int type Pole = (Birds, Birds) landLeft :: Birds -> Pole -> Pole landLeft n (left, right) = (left + n, right) landRight :: Birds -> Pole -> Pole landRight n (left, right) = (left, right + n) main = do print $ landLeft 2 (0, 0) print $ landRight 1 (1, 2) print $ landRight (-1) (1, 2)
Scala(Z)で書くとこう。
def routine: Option[Pole] = for { start <- Monad[Option].point(Pole(0, 0)) first <- start.landLeft(2) _ <- (none: Option[Pole]) second <- first.landRight(2) third <- second.landLeft(1) } yield third println(routine)