Skip to content

Memoisation, Currying, Uncurrying and Type Inferencing

johnmcclean-aol edited this page Nov 22, 2016 · 9 revisions
screen shot 2016-02-22 at 8 44 42 pm

Cyclops Functions

Memoisation

com.aol.cyclops.functions.Memoize contains a number of methods for memoising JDK 8 Functional interfaces. Supplier, Callable, Function, BiFunction and Predicates.

Example memoising a Supplier

		Supplier<Integer> s = Memoize.memoizeSupplier(()->++called);
		assertThat(s.get(),equalTo(1));
		assertThat(s.get(),equalTo(1));

Example use in action - automatic Memoization / caching in simple-react

Currying

com.aol.cyclops.functions.Curry provides methods to curry Functions of up to 8 parameters. The package com.aol.cyclops.functions also defines functions of between 3 and 8 parameters to support this.

com.aol.cyclops.functions.CurryConsumer provides methods to curry Consumers of up to 8 parameters.

Example Currying a BiFunction

		assertThat(Curry.curry2((Integer i, Integer j) -> "" + (i+j) + "hello").apply(1).apply(2),equalTo("3hello"));

Example Currying a Method Reference

      assertThat(Curry.curry2(this::mult).apply(3).apply(2),equalTo(6));

Uncurrying

com.aol.cyclops.functions.Uncurry has methods to uncurry nested curried Functions of up to 8 levels deep. com.aol.cyclops.functions.UncurryConsumer does the same thing for curried Consumers up to 5 levels deep.

Example Uncurrying a function to a function that takes 4 parameters

     assertThat(Uncurry.uncurry4((Integer a)->(Integer b)->(Integer c)->(Integer d)->a+b+c+d)
				.apply(1,2,3,4),equalTo(10));

Type inferencing

The class com.aol.cyclops.lambda.utils.Lambda provides static helper methods for defining curried Lambda expressions of up to 8 nested Functions.

Example in conjunction with Lombok val

     val fn  = λ3((Integer a)-> (Integer b)->(Integer c) -> a+b+c)
Clone this wiki locally