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

Re: the benefits of immutability



Quoting vkarvone@mappi.helsinki.fi:
> 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.

Oops, there were (two) bugs in the code I posted! My apologies for the extra
bandwidth, but here is a semantically nicer version:

public class FunctionalJava {

  public static class Fn {
    public Object body(final Object x) {
      return x;}}


  public static final Object apply(Object fn, Object x) {
    return ((Fn)fn).body(x);}


  public static final Fn
    IDENTITY = new Fn(),
    SQRT = new Fn() {
        public Object body(final Object x) {
          return new Double(Math.sqrt(((Double)x).doubleValue()));}},
    TO_STRING = new Fn() {
        public Object body(final Object x) {
          return x.toString();}},
    COMPOSE = new Fn() {
        public Object body(final Object f) {
          return new Fn() {
              public Object body(final Object g) {
                return new Fn() {
                    public Object body(final Object x) {
                      return apply(f,apply(g,x));}};}};}};


  public static final void main(String argv[]) {
    System.out.println(apply(apply(apply(COMPOSE,TO_STRING),SQRT),
                             new Double(10)));}
}

Regards,
  Vesa Karvonen

P.S.: I'm not endorsing this as a good style to program functionally in
Java. One of the biggest problems is the lack of tail recursion optimization.