[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: the benefits of immutability



Quoting Joe Marshall <jrm@ccs.neu.edu>:
> [...] write the following in Java:
> 
> (defun compose (f g)
>     (lambda (x) (funcall f (funcall g x))))
> 
> and use it to compose the square root function and the
> ToString function to create a function that takes numbers
> and produces the printed representation of their square root.

public class FunctionalJava {
  public static class Fn {
    public Object ap(Object a) {
      return a;
    }
  }

  public static final Fn
    sqrt = new Fn() {
        public Object ap(Object a) {
          return new Double(Math.sqrt(((Double)a).doubleValue()));}},
    toString = new Fn() {
        public Object ap(Object a) {
          return a.toString();}},
    compose = new Fn() {
        public Object ap(final Object a) {
          return new Fn() {
              public Object ap(Object b) {
                return ((Fn)((Object[])a)[1]).ap(((Fn)((Object[])a)[1]).ap(b));
              }
            };
        }
      };

  public static void main(String argv[]) {
    System.out.println( ((Fn)(compose.ap(new
Object[]{sqrt,toString}))).ap(new Double(10)) );
  }
}

> Extra credit if you can do it in 240 characters.  (three 80 character
> lines)

Guess I didn't get the extra credit. ;)

Regards,
  Vesa Karvonen