-
Notifications
You must be signed in to change notification settings - Fork 136
Ior
Ior can be one of Primary, Secondary or Both Primary and Secondary, and as such it can behave either like a product (Tuple) or sum (either) type. As an Either or Union type, it is right biased. Primary and Secondary are used instead of Right & Left.
Ior inherits from the following cyclops types (and others) ApplicativeFunctor, Filterable, Foldable, Functor, MonadicValue1, To, Value,Visitable and Zippable.
Loosely based on Ior from Cats, Ior does not accumulate values automatically on flatMap. Future releases will allow Ior to accumulate primary and secondary values simultaneously.
Right' (or primary type) biased disjunct union. No 'projections' are provided, swap() and secondaryXXXX alternative methods can be used instead.
Ior.<Integer,Integer>primary(10)
.map(i->i+1);
//Ior.primary[11]
Ior.<Integer,Integer>secondary(10)
.map(i->i+1);
//Ior.secondary[10]
Ior.<Integer,Integer>secondary(10)
.swap()
.map(i->i+1);
//Ior.primary[11]
Ior<String,Ingeger> kv = Ior.both("hello",90);
//Ior["hello",90]
See also Ior in Cats
Ior can operate (via flatMap) as a Monad and via combine as an ApplicativeFunctor
Values can be accumulated via
Ior.accumulateSecondary(ListX.of(Ior.secondary("failed1"),
Ior.secondary("failed2"),
Ior.primary("success")),
Semigroups.stringConcat)
//failed1failed2
Ior<String,String> fail1 = Ior.secondary("failed1");
fail1.swap().combine((a,b)->a+b)
.combine(Ior.secondary("failed2").swap())
.combine(Ior.<String,String,String>primary("success").swap())
//failed1failed2
Conversely accumulatePrimary is also available.
Combine values of any type asynchronously
Ior.primary(10)
.combine(Maybe.just(10),(a,b)->a+b);
//Primary[20]
orElse and coflatMap can be used to manage Xor's that aren't present and provide a default value.
int result = Ior.primary(10)
.orElse(-1); //10
int result = Ior.secondary("hello")
.orElse(-1); //-1
Ior.secondary()
.coflatMap(xor->xor.visit(s->10,p->p,(b1,b2)->-1); //Ior.Primary[10]
We can use the visit method to execute a function depending on whether the Ior is primary or secondary
Ior.secondary(10)
.visit(s->"This is secondary",p->"This is primary",b->"both"); //returns This is secondary
Ior.primary(10)
.visit(s->"This is secondary",p->"This is primary",(b1,b2)->"both"); //returns This is primary
Ior.both(10,20)
.visit(s->"This is secondary",p->"This is primary",(b1,b2)->"both"); //returns both
oops - my bad