Skip to content
johnmcclean-aol edited this page Feb 24, 2016 · 8 revisions

Cyclops has merged with simple-react. Please update your bookmarks (stars :) ) to https://github.com/aol/cyclops-react

All new develpoment on cyclops occurs in cyclops-react. Older modules are still available in maven central.

screen shot 2016-02-22 at 8 44 42 pm

Matching against an Optional

Matchable.of(Optional.of(3))
	 .matches(
	           o-> o.isEmpty().then(i->"hello"),
	           o-> o.hasValues(1).then(i->""+2),
	           o-> o.hasValues(2).then(i->""+3),
	           o-> o.hasValues(3).then(i->""+4)
	          )

//4

mayMatch against an Optional

Optional<String> result = Matchable.of(Optional.empty()).mayMatch(c->c.isEmpty().then(i->"hello"))

//Optional["hello"]

Match by type, any value acceptable

Matchable.of(1)
	 .matches(c->c.isType((Integer it)->"hello").anyValues())
//hello

Match against a list of values (syntax sugar for list creation)

Matchable.listOfValues(1,2,3)
							        .matches(c->c.hasValuesWhere((Object i)->(i instanceof Integer)).then(i->2)
//2

Recursive example

Matchable.listOfValues(1,new MyCase(4,5,6))
	 .matches(c->c.hasValues(Predicates.__,Predicates.hasValues(4,5,6)).then(i->"rec"));

//rec

Recursive example with static imports

Matchable.listOfValues(1,new MyCase(4,5,6))
	 .matches(c->c.hasValues(__,hasValues(4,5,6)).then(i->"rec"));

//rec

Match by type with values

Matchable.of(new Child(10,20))
         .matches(
		  c-> c.isType( (Child child) -> child.val).hasValues(10,20)
		)

@Value
static class Child extends Parent{
       int nextVal;
       public Child(int val,int nextVal) { super(val); this.nextVal = nextVal;}
}
@AllArgsConstructor(access=AccessLevel.PACKAGE)
static class Parent{
	int val;
}

Examples from simple-react

Convert integer to either even or odd

List<String> result = LazyFutureStream.of(1,2,3,4)
				      .capture(e->e.printStackTrace())
				      .patternMatch("",
							c->c.hasValuesWhere( (Integer i)->i%2==0 ).then(i->"even"),
							c->c.hasValuesWhere( (Integer i)->i%2!=0).then(i->"odd")
						    )
						    .toList();
assertThat(result,equalTo(Arrays.asList("odd","even","odd","even")));

Decompose values in a Stream

List<String> result = LazyFutureStream.of(new MyCase(1,2),new MyCase(3,4))
					.capture(e->e.printStackTrace())
					.patternMatch("n/a",
							 c->c.hasValues(1,2).then(i->"one"),
							 c->c.hasValues(3,4).then(i->"two"),
							 c->c.hasValues(1,4).then(i->"three"),
							 c->c.hasValues(2,3).then(i->"four")
													  
							)
							.toList();
assertThat(result,equalTo(Arrays.asList("one","two")));
Clone this wiki locally