-
Notifications
You must be signed in to change notification settings - Fork 136
Maybe
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.
Maybe is an instance of the following cyclops types (and others) ApplicativeFunctor, Filterable, Foldable, Functor, MonadicValue1, To, Value,Visitable and Zippable
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 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]
Combine values of any type asynchronously
Maybe.just(10)
.combine(Xor.primary(10),(a,b)->a+b);
//Maybe[20]
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));
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)
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))));
}
oops - my bad