Skip to content

Instantly share code, notes, and snippets.

@tobyweston
Last active December 19, 2015 22:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobyweston/6027570 to your computer and use it in GitHub Desktop.
Save tobyweston/6027570 to your computer and use it in GitHub Desktop.
Currying in Java (and partial application of function example)
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));
}
}
@tobyweston
Copy link
Author

add(1, 1, 1) = 3
add().apply(1) = Function1<[A, B]>
add().apply(1).apply(1) = 2

@tobyweston
Copy link
Author

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