Saturday, June 12, 2010

One reason I'm falling in love with Erlang

One reason I'm falling in love with Erlang is its brevity.

For example, here is an example from Joe Armstrong's book "Programming Erlang" (ISBN 978-1-934356-00-5):


-module(geometry). -export([area/1]). area({rectangle, Width, Height}) -> Width * Height; area({circle, R}) -> 3.14159 * R * R; area({square, Side}) -> Side * Side.

A Python version is not too wordy, though not as clear:


def area(type, *args) if len(args) < 1 or len(args) > 2: raise Exception("Invalid number of arguments") if type == 'rectangle': return args[0] * args[1] if len(args) != 1: raise Exception("Too many arguments") if type == 'circle': return 3.1459 * args[0] * args[0] if type == 'square': return args[0] * args[0] raise Exception("type of shape not recognised")

but the Java version is, by comparison, ridiculous. Four separate files are combined here for (a sort of) clarity:


################### ### Shape.java #### ################### package geometry; public interface Shape { public Number area(); } ##################### #### Circle.java #### ##################### package geometry; public class Circle implements Shape { final private Number radius; public Circle(Number radius) { this.radius = radius; } @Override public Number area() { return Math.PI * radius.doubleValue() * radius.doubleValue(); } } ######################## #### Rectangle.java #### ######################## package geometry; public class Rectangle implements Shape { final Number height; final Number width; final boolean isDouble; public Rectangle(Number width, Number height) { this.height = height; this.width = width; this.isDouble = (width instanceof Double || height instanceof Double || width instanceof Float || height instanceof Float); } @Override public Number area() { if (this.isDouble) { return width.doubleValue() * height.doubleValue(); } else { return width.longValue() * height.longValue(); } } } ##################### #### Square.java #### ##################### package geometry; public class Square implements Shape { final Number side; final boolean isDouble; public Square(Number side) { this.side = side; this.isDouble = (side instanceof Double || side instanceof Float); } @Override public Number area() { if (this.isDouble) { return side.doubleValue() * side.doubleValue(); } else { return side.longValue() * side.longValue(); } } }

No comments: