Skip to content
Robert Peszek edited this page Sep 14, 2013 · 1 revision

Either Type

Type fpig.common.types.Either<L,R> does not define any methods and should be used only in declarations. Instead, programs should use functions defined in fpig.common.functions.FpigBase.

Either is typically used to put things in a context of possible error and is functional alternative to throwing Exceptions.
Example:

Closure diet = { person ->
  if(person.weight>150)
     right([name:person.name, weight: person.weight-20])
  else
     left('eat more, you are too skinny')
}

Here is the functional API usage:

assert isRight(right('test'))
assert !isRight(left('error')) 

assert unright(right(10)) == 10
assert unleft(left(0)) == 0

Either as Monad

Either monad description is defined by fpig.common.functions.EitherMonad class and this description is registered with Fpiglet.

Example:

def jon = ...
MonadDescription m = EitherMonad.instance       
Either after2Diets = m.bind(diet) << m.bind(diet) << m.pure(jon) 

See MonadPolymorphism and /test/fun.by_example/EitherInsteadOfExceptions_ExpoTests.groovy.

Clone this wiki locally