Skip to content
johnmcclean-aol edited this page Nov 23, 2016 · 10 revisions

The Maybe type in cyclops-react is a totally lazy Option or Optional type modelled on Maybe from Haskell. Maybe's can represent one of two states - Just a value (present / some ) or None.

Class Hiearchy

Maybe

Maybe is an instance of the following cyclops types (and others) ApplicativeFunctor, Filterable, Foldable, Functor, MonadicValue1, To, Value,Visitable and Zippable

Pattern matching

In cyclops we can use the visit operator to pattern match on the state the Maybe is in.

int result = Maybe.just(10)
                  .visit(some->some+5,()->-1); 

Recover / orElse /coflatMap

Recover orElse and coflatMap can be used to manage Maybe's that aren't present and provide a default value.

Maybe.just(10)
     .recover(-1); //Maybe[10]
Maybe.none()
     .recover(-1); //Maybe[-1]
 

int result = Maybe.none()
                  .orElse(-1); //-1

Maybe.none()
     .coflatMap(maybe->maybe.visit(v->v,()->-1); //Maybe[-1]

Applicative Functor

Combine values of any type asynchronously

Maybe.just(10)
       .combine(Xor.primary(10),(a,b)->a+b);
//Maybe[20]

Sequence

Sequence takes a List or Stream of Maybe's and converts it to a Maybe with a List or Stream.

Maybe<Integer> just = Maybe.just(10);
Maybe<Integer> none = Maybe.none();

Maybe<ListX<Integer>> maybes = Maybe.sequence(ListX.of(just, none, Maybe.just(1)));
//Maybe.none();

Maybe<ListX<Integer>> maybes = Maybe.sequenceJust(ListX.of(just, none, Maybe.just(1)));
//Maybe.just(ListX.of(10, 1));

Accumulating

Accumulate allows us to accumulate the present values in a List of Maybes.

Maybe<Integer> just = Maybe.just(10);
Maybe<Integer> none = Maybe.none();

Maybe<Integer> maybes = Maybe.accumulateJust(Monoids.intSum,ListX.of(just, none, Maybe.just(1)));
//Maybe.just(11)

Recursion

Maybe's functor and monad operations have built in trampolines for stack safe recursion, so this doesn't blow the stack!

@Test
public void fib() {
   System.out.println(fibonacci(just(tuple(100_000, 1l, 0l))));
}

public Maybe<Long> fibonacci(Maybe<Tuple3<Integer, Long, Long>> fib) {
    return fib.flatMap(t -> t.v1 == 0 ? just(t.v3) : 
                         fibonacci(just(tuple(t.v1 - 1, t.v2 + t.v3, t.v2))));
}
Clone this wiki locally