Closures Currying Example - UnquietCode/Closures-for-Java GitHub Wiki

These examples and more are located in the repository under '/src/test/java/unquietcode/stately/closure/'.

	public void simpleCurryExample() {
		Closure1<String, String> c1 = new AbstractClosure1<String, String>() {
			String greeting = "Hello";
			char ending = '.';

			public String run(String p1) {
				return greeting + " " + p1 + ending;
			}
		};

		// normal
		String name = "world";
		out(c1.run(name));      // Hello world.

		// curried
		c1.curry(1, "Goodbye");
		c1.curry(2, '!');
		out(c1.run(name));      // Goodbye world!
	}

	public void advancedCurryExample() {
		// Currying is supported by the Closure classes.
		// As in other places, indexing is 1-based.
		// We'll again use the adderFactory example to demonstrate this feature.

		Closure1<Closure1<Integer, Integer>, Integer> adderFactory = new AbstractClosure1<Closure1<Integer, Integer>, Integer>() {
			int declaredValue1 = 1;     // factory variable #1
			int declaredValue2 = 10;    // factory variable #2

			public Closure1<Integer, Integer> run(Integer p1) {
				return new AbstractClosure1<Integer, Integer>(p1) {
					Integer declaredValue3 = a1();  // adder variable #1
					
					// these variables aren't automatically segregated, so we have to
					// defensively copy
					int myDeclaredValue1 = declaredValue1;
					int myDeclaredValue2 = declaredValue2;

					public Integer run(Integer p1) {
						// Note that if we had used a1() down here, the value would not have been curried!
						return myDeclaredValue1 + myDeclaredValue2 + declaredValue3 + p1;
					}
				};
			}
		};

		// normal
		Closure1 tarragon = adderFactory.run(100);  // will add 1 + 10 + 100 + x
		out(tarragon.run(5));                       // which gives us 116

		// The returned adder has 1 field, declaredValue3, that we can modify
		tarragon.curry(1, 110);                     // change to add 1 + 10 + 110 + x instead
		out(tarragon.run(5));                       // now we get 126!

		// we can change the factory too, though
		adderFactory.curry(1, 15);
		adderFactory.curry(2, 20);
		Closure1 cardamom = adderFactory.run(100);  // will add 15 + 20 + 100 + x
		out(cardamom.run(5));                       // which gives us 140
	}