Last active
December 19, 2015 22:29
-
-
Save tobyweston/6027570 to your computer and use it in GitHub Desktop.
Currying in Java (and partial application of function example)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.googlecode.totallylazy.Function1; | |
import java.util.Arrays; | |
import static java.lang.String.*; | |
public class CurryingExample { | |
static abstract class Function1<A, B> extends com.googlecode.totallylazy.Function1<A, B> { | |
@Override | |
public String toString() { | |
Class<?> function = getClass().getSuperclass(); | |
return format("%s<%s>", function.getSimpleName(), Arrays.toString(function.getTypeParameters())); | |
} | |
} | |
public static int add(int a, int b, int c) { | |
return a + b + c; | |
} | |
public static Function1<Integer, Function1<Integer, Integer>> add() { | |
return new Function1<Integer, Function1<Integer, Integer>>() { | |
@Override | |
public Function1<Integer, Integer> call(final Integer first) throws Exception { | |
return new Function1<Integer, Integer>() { | |
@Override | |
public Integer call(Integer second) throws Exception { | |
return first + second; | |
} | |
}; | |
} | |
}; | |
} | |
public static void main(String... args) { | |
System.out.println("add(1, 1, 1) = " + add(1, 1, 1)); | |
System.out.println("add().apply(1) = " + add().apply(1)); | |
System.out.println("add().apply(1).apply(1) = " + add().apply(1).apply(1)); | |
} | |
} |
Author
tobyweston
commented
Jul 18, 2013
Scala
object CurryExample {
// def add(x: Int, y: Int): Int = {
// x + y
// }
// shortcut
def add(x: Int)(y: Int): Int = {
x + y
}
def addLongHand(x: Int): (Int => Int) = {
(y: Int) => {
x + y
}
// return new Function[Int, Int] {
// override def apply(y: Int) = x + y
// }
}
def main(args: Array[String]) {
// println("add(1, 2) = " + add(1, 2))
println("add(1) = " + add(1) _)
println("add(1) = " + add(1) _)
println("(add(1) _).apply(2) =" + (add(1) _).apply(2))
println("add(1)(2) = " + add(1)(2))
println("addLongHand(1)(2) = " + addLongHand(1).apply(2))
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment