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

Re: the benefits of immutability



From: vkarvone@mappi.helsinki.fi
Subject: Re: the benefits of immutability
Date: Tue, 19 Aug 2003 19:27:16 +0300

> 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)) );
>   }
> }

Sorry, your program is too complex (contrary to original version in
lisp) to be written without errors.

line:
     return ((Fn)((Object[])a)[1]).ap(((Fn)((Object[])a)[1]).ap(b));
should be:
     return ((Fn)((Object[])a)[1]).ap(((Fn)((Object[])a)[0]).ap(b));

Or otherwise you are composing toString with toString, which yields
result 10.


toString is particularly bad example since toString conversion is what
Java does anyway.

Following function for composition with sqrt makes a better example:
    addOne = new Fn() {
        public Object ap(Object a) {
            return new Double(((Double)a).doubleValue()+1);}}



Best regards,

Jakub Travnik
jabber://jtra@jabber.com