Friday, June 01, 2007

A very dumb neural network in Haskell

Continuing my implementations of Michael Negnevitsky book on Artifical Intelligence in Haskell, I have tried to code a three layer neural network to implement exclusive or (Intelligence indeed...).

A neuron is made of its input weight and its threshold, and its output is calculated thus (apologies to all of you who gave me some tips about parameter order and newtype declaration, I haven't changed the code yet to follow your good advice!):

type Neuron= ([Value],Value)
type Value = Float

neuronOutput :: [Value] -> Neuron -> Value
neuronOutput inputs (weights,threshold) =
let
tot=(foldl (+) 0 (zipWith (*) inputs weights)) - threshold
in
1 / (1 + ((2.7182) ** (-tot)))


A three layer network whose input layer does nothing but fire its input to the midle layer can be modelled by to lists of neurons, and I use a TestCase type to keep track of inputs and expected outputs
       
type Network = ([Neuron],[Neuron])
type TestCase = ([Value],[Value])

Running the whole network with some input values is easy:

exec :: Network -> [Value] -> ([Value],[Value])
exec (hidden,output) inputs =
let
hiddenOutputs = map (neuronOutput inputs) hidden
outputOutputs = map (neuronOutput hiddenOutputs) output
in
(hiddenOutputs,outputOutputs)

The meat is all in one function, that calculates the output of the network for a given test and adapts the weights accordingly, first for the output layer then for the hidden layer:

defaultLearningRate::Value
defaultLearningRate=0.1

step :: (Network,Value) -> TestCase -> (Network,Value)
step ((hidden,output),err) (inputs,expected)=
let
(hiddenOutputs,outputOutputs)=exec (hidden,output) inputs
errorOutputs= zipWith (-) expected outputOutputs
gradientOutputs=zipWith (\o d->o*(1-o)*d) outputOutputs errorOutputs
newOutputs=zipWith (\(ws,t) g -> ( zipWith (\h w->w+ (defaultLearningRate*h*g)) hiddenOutputs ws ,t+(defaultLearningRate*g*(-1)))) output gradientOutputs
weightsByHidden= transpose (map fst output)
gradientHidden =zipWith (\o ws-> o * (1-o) * (foldl (+) 0 (zipWith (*) ws gradientOutputs))) hiddenOutputs weightsByHidden
newHidden=zipWith (\(ws,t) g -> ( zipWith (\h w->w+ (defaultLearningRate*h*g)) inputs ws ,t+(defaultLearningRate*g*(-1)))) hidden gradientHidden
newErr=err + (foldl (+) 0 (map (^2) errorOutputs))
in ((newHidden,newOutputs),newErr)

The result is a new adapted network and the sum of squared errors.

An epoch is a set of tests:

epoch :: Network -> [TestCase] -> (Network,Value)
epoch network= foldl step (network,0)

We can then repeat epoch till the sum of squared errors for an epoch is less than the threshold for convergence:

errorConvergence::Value
errorConvergence=0.001

run :: Network -> [TestCase] -> Int -> (Network,Int,Value)
run network allInputs epochNb=
let (newNetwork,delta) = epoch network allInputs
in (?) (delta <= errorConvergence || epochNb>225)
(newNetwork, epochNb,delta)
(run newNetwork allInputs (epochNb+1))

(?) :: Bool -> a -> a -> a
(?) True a _ = a
(?) False _ a = a

(Is there a standard function for (?)? I got tired of if then else...)

Then I test my code with the same start network as in the book:

test = do
let n = ([([0.5,0.4],0.8),([0.9,1.0],-0.1)],[([-1.2,1.1],0.3)])
let (n',e,err) = run n [([1,1],[0]),([0,1],[1]),([1,0],[1]),([0,0],[0])] 1
print (n',e,err)
return ()

And I get a mixed feeling about the result: the network does converge, and then it does work, but after something like 54000 epochs, while in the book it supposedly take 224! The book gives the result for the first test and I'm getting exactly the same thing, but it looks like my network learns a lot slower than it should. I would suppose I have a subtle error somewhere, but for the life of me I can't find it... If it jumps at anybody, please let me know. My hope now is that when refactoring the code and following the books advice on improving the performance I will find the bug!!

I have tried with random networks:

network :: Int -> Int -> Int-> IO Network
network inputNb hiddenNb outputNb= do
a<-randomNeurons inputNb hiddenNb
b<-randomNeurons hiddenNb outputNb
return (a,b)

randomNeurons:: Int -> Int -> IO [Neuron]
randomNeurons nbInput nbNeurons= replicateM nbNeurons (randomNeuron nbInput)

randomNeuron:: Int -> IO Neuron
randomNeuron nb= do
w<-replicateM nb (randomWeight nb)
t<-randomWeight nb
return (w,t)

randomWeight:: Int -> IO Value
randomWeight nbInput= do
let interval= randomR ((-2.4)/(fromIntegral nbInput),2.4/(fromIntegral nbInput))
getStdRandom interval

But I don't get better results...

Friday, May 25, 2007

A perceptron in Haskell

After reading Michael Negnevitsky book on Artifical Intelligence, I started playing with some of the algorithms he gives in Haskell. So my first endeavour is writing a simple perceptron (a one neuron neural network) to perform AND or OR logical operations. Next I'll start a full multi layer network to do much more complex operations like exclusive OR (-:.
Once again I was struck with the simplicity of the Haskell code necessary to implement such functionality (and I'm no Haskell expert yet). You think about how you going to implement it, the type checker tells you when you're doing something stupid, and by the time everything is written and compiles it kinda works.
The core method is calculating the output of the neuron, given the inputs, the weight of each input and the threshold value for that neuron:

neuronOutput :: [Float] -> [Float] -> Float -> Float
neuronOutput inputs weights threshold =
let
tot=(foldl (+) 0 (zipWith (*) inputs weights)) - threshold
in
if tot >= 0
then 1
else 0

Using zipWith we multiply each input with its weigth, calculate the sum with fold and remove the threshold. A negative result yields 0, else it yields 1.

Adjusting the weights to adapt to the error of a test case is no more difficult:

defaultLearningRate::Float
defaultLearningRate=0.1

adjustWeights :: [Float] -> [Float] -> Float -> Float -> [Float]
adjustWeights inputs origWeights expected actual =
let
e=expected - actual
delta (i,w) = w + (defaultLearningRate * i * e)
in
map delta (zip inputs origWeights)

We modify the weight by applying to each weight a delta that is dependant on the input weight, the error ratio and the learning rat

A single step is made of calculating the output of the neuron and adapting the weights, given the expected value:

defaultThreshold::Float
defaultThreshold=0.2

step :: [Float] -> [Float] -> Float -> [Float]
step inputs weights expected=
let
o = neuronOutput inputs weights defaultThreshold
in
adjustWeights inputs weights expected o

Then an epoch applies the step function to each different input sets. The hardest part is calculating the average of all deltas to find if the weights have changed at all during the evaluation of all the test cases

epoch :: [([Float],Float)] -> [Float] -> ([Float],Float)
epoch allInputs weights=
let
f w (inputs,expected) = step inputs w expected
newWeights=foldl f weights allInputs
delta= (foldl (+) 0 (map abs (zipWith (-) newWeights weights))) / (fromIntegral $ length weights)
in (newWeights,delta)

A training run is only launching the epoch function repeatedly till the delta is zero:

run :: [([Float],Float)] -> [Float] -> Int -> ([Float],Int)
run allInputs weights epochNb=
let (newWeights,delta) = epoch allInputs weights
in if delta == 0
then
(newWeights, epochNb)
else
run allInputs newWeights (epochNb+1)

We generate the initial weights in the IO monad, passing the number of weights needed:

initialWeights :: Int -> IO [Float]
initialWeights nb = do
let interval= randomR (-0.5,0.5)
(replicateM nb (getStdRandom interval))

Putting it all together:

test :: IO()
test = do
w<-initialWeights 2
let (ws,i)=run [([0,0],0),([0,1],0),([1,0],0),([1,1],1)] w 1
print (ws,i)
return ()

test find out the proper weights to implement AND and print them out, with the number of epochs needed to reach the result. You can then call neuronOutput with the resulting weights and your input: you have a AND logical gate!

As usual, any pointer to how to improve the code is welcome!

Wednesday, May 16, 2007

Javascript and Hibernate, hand in hand

Some time ago I had written a little prototype that was quite interesting, but I never pursued it. Maybe I should try to get some people interested and develop it further...
The idea was to use Rhino to have a Javascript-based framework on the server, thus using the same language on the server and on the client, like ASP did in the good old days. I was also thinking of having the source code for custom applications stored in the database, instead of having it in source files, but that's another story. That explains why the examples below are about "applications" and "components"
The first component is Hibernate connectivity. My framework lets you:
1. Dynamically configure Hibernate mapping for Javascript defined classes. For example, if you wanted to define a Web Application with several attributes and a reference to the components that it defines:

function Application(){
this.displayName='';
this.urlName='';
this.defaultUrl='';
this.id=-1;
this.components=[];
}


Application.storage(
{
id:
{name:'id',column:'ID',type:'long'},
properties:
[
{name:'displayName','not-null':true},
{name:'urlName','not-null':true,unique:true,'unique-key':'APPLICATION_URL'},
{name:'defaultUrl'}
],
references:
[
{'list':
{name:'components',table:'APPLICATION_COMPONENT',
details:[
{'key':{column:'APPLICATIONID'}},
{'list-index':{column:'idx',base:'0'}},
{'many-to-many':{'column':'COMPONENTID','class':'Component'}}
]
}
}
]
}
);

Note that storage() is a function of the Function object which takes a Javascript structure that mimicks the Hibernate XML.

2. Access Hibernate functionality through a "hibernate" host object. For example, a JSUnit method testing the addition of a new "Application" object:

var appId;
var appUrlName;

function testAdd(){
assertNotUndefined(hibernate);
var app=new Application();
assertNotUndefined(app);
app.displayName="TestAppJS"+new Date();
app.urlName=app.displayName;
appUrlName=app.urlName;
hibernate.save(app);
hibernate.commit();
assertNotNaN(app.id);
assertTrue(app.id>0);
appId=app.id;
}

The hibernate object lets you list objects, get a particular object, modify or create instances, etc. I have implemented a Hibernate EntityTuplizer and an subclass of Rhino's NativeArray that encapsulate a PersistentList, so that multiples references can be seen as Javascript arrays.

3. Query the database either through the HQL language:

var apps=hibernate.query("from Application where urlName=?",["TestAppJS"]);

or through a pure Javascript function based mechanism:

var apps=hibernate.query("Application",function(app){
return app.urlName=="TestAppJS";}
);

That I think is very cool. In Rhino I can access the source code of the function that is passed as the second argument to query, and transform it into HQL. I haven't implemented as much as I could, of course, but it works with simple queries. At least there is no other syntax to learn to do a query, it's basically the equivalent of a filter function in functional language.

Then I had started to develop a web framework (probably the millioneth Java web framework by now) with Javascript objects to generate HTML and a mapping between urls and javascript functions, and where one URL could chain several functions, but I haven't gone very far.

Now if somebody feels there's some value in any of that I can sure post the code and we can move it forward. Anything that can show that Javascript is a cool language to run in a JVM in a worthwhile enterprise (-:

Friday, May 11, 2007

Poor man's JavaFX Script is, er... Javascript

Sun has release its own RIA framework called Java FX. It provide JavaFX Script, which is a language based on Java whose goal is to develop quickly graphical applications with the power of Java. Is it touted as competition to Flex that I have mentioned before. It is safe to say that it hasn't been received with a great deal of enthusiasm. The fact is, I don't want to learn another language again to do my Web 2.0 application. And I do believe that Fielding has a point when he reflects that applets break visibility and raise the barrier of entry for web developers. Also, I'm usually all in favor of static typing and compilation, but for GUIs I'm not too sure. When you want to tweak your borders or your layouts you probably happy enough with a quick cycle of change code/refresh page. So why don't we use Javascript and Java Applets together instead of inventing yet another technology?
Ok, it's time you get over your irrational distrust of Javascript. A multi paradigm (object, functional) language available for free in every browser!! And no, I don't suggest we go on using the HTML DOM or things like that. That's why we need applets.
Applets? I must be mad! Applets have not worked on the web. But what I suggest is not to develop one applet for each RIA application, but only develop one Applet that everybody could use, much like a plugin, that would bridge the gap between the JavaScript world and the Java/Swing world. If it has been done, please let me know. As for me, I've put together a prototype in an hour that works fine:
  1. The JavaScript code constructs an object tree that represents the GUI.
  2. The object tree is serialized to JSON and passed on to the applet
  3. The applet deserializes the JSON and constructs a Swing GUI by translating the object tree
  4. The object tree can contain handlers that are the names of Javascript functions
  5. The applet calls the javascript functions on Swing events
  6. The JavaScript event handlers update the GUI tree and notify the applet with the changes.
A very simple example:


<html>
<head><title>JSApplet</title>

<script language="Javascript">

var helloButton={type:"button","id":"helloButton","text":"hello","action":onClickHello}
var frame={"contents":
[
helloButton
]
};


function onClickHello(){
helloButton.text=helloButton.text.toUpperCase();
updateJS([helloButton])
}

function startJS(){
var msg=document.getElementById("JSApplet").setContent(toJSON(frame));
if (msg){
alert(msg);
}
}

function updateJS(objs){
var msg=document.getElementById("JSApplet").updateContent(toJSON(objs));
if (msg){
alert(msg);
}
}


toJSON=function(arg) {

switch (typeof arg) {
case 'object':
if (arg) {
if (arg.constructor == Array) {
var o = '';
for (var i = 0; i < arg.length; ++i) {
var v = toJSON(arg[i]);
if (o) {
o += ',';
}
if (v != null) {
o += v;
} else {
o += 'null,';
}
}
return '[' + o + ']';
} else if (typeof arg.toString != 'undefined') {
var o = '';
for (var i in arg) {
var v = toJSON(arg[i]);
if (v != null) {
if (o) {
o += ',';
}
o += toJSON(i) + ':' + v;
}
}
return '{' + o + '}';
} else {
return;
}
}
return 'null';
case 'unknown':
case 'undefined':
case 'function':
return arg.name;
case 'string':
return '"' + arg.replace(/(["\\])/g, '\\$1') + '"';
default:
return String(arg);
}
}

</script>
</head>
<body onload="startJS();">
<applet id="JSApplet" alt="JSApplet" code="fr/moresmau/jp/jsapplet/JSApplet.class" codebase="bin" mayscript="mayscript" height="100" width="100"></applet>



</body>
</html>


This web page creates a simple "Hello" button that when clicked changed its text to upperCase(). It demonstrate the two ways communication between the Javascript code and the applet (note how the function is serialized in JSON just with its name, that's the only thing we need). So the Javascript can deal with a model that is a slightly abstracted Swing model (no more hair pulling between different browsers). I stress again, the applet is a generic applet that deals with the link between the JSON objects and the Swing layer. Of course the applet could offer other services: simple API to call back the server (AJAX from the applet), etc...
Then the applet could be packaged with a cut down version of the JRE (only the classes really needed) as a plugin to do rich Swing application from JavaScript...
And voilĂ ! A scriptable RIA platform!

Friday, April 20, 2007

Haskell code, Java UI

It's been while since I've posted anything, mainly because work crises and holidays have kept me busy or away from my keyboard. I'm still playing with Haskell and user interfaces, I've now developed the same Maze game in HGL, Flex with a Haskell web back end, and WXHaskell. I've looked at trying to implement some declarative syntax that would simplify WXHaskell code but haven't gone very far, I think I'm trying to run in Haskell before I can walk straight!
Anyway, I was looking at Business Objects' Quark framework based on the CAL language. You can find more details here, but basically CAL is a Haskell-inspired impure functional language implemented in Java, that can use Java classes and methods. The impurity comes from not using monads to access Java, if I understand well, which means that you can declare pure functional methods that in fact access Java objects, that can do all kind of stateful voodoo under the covers. While I'm not sure this is really A Good Thing, having Haskell and Java intertwined brings some interesting ideas in the realm of Haskell UIs. Swing and Java are now mature, reasonably fast and cross platform. If I can get my pure Haskell code to talk to a Java GUI, I could get quite happy indeed...

Friday, March 30, 2007

A Haskell GUI in Flex

In an earlier post I mentioned a little Haskell game I developed where you had to navigate in a maze. I used HGL as the GUI framework, and noted it wasn't very clear what was the functional GUI framework of choice for Haskell. So I decided to give Flex a go and to hook it up with my Haskell back-end. I'm quite please with the result, I have to say.
The setup is as follows:
1) I've implemented a very simple single-threaded HTTP server in Haskell, using as an inspiration code that I found here and there (using Parsec for parsing HTTP messages, etc.). The server can server static HTML and SWF files as well as having a dynamic component: you can register Haskell methods that take a JSON object as a parameter, some internal state and return a new JSON object and the new state (yes I know, there is a monad for that...). I used the code here for JSON in Haskell. I thus expose a method that generates a Maze and a method to move to a cell, validating that there is no wall in between the current cell and the target cell and checking to see if we reached the exit.
2) I use Flex and ActionScript to create the GUI. The compiled SWF file will be served by the Haskell server and will call it back through asynchronous calls. I was a bit taken aback when I realized that Flex doesn't come with JSON support out of the box, but luckily there's a library for it. So you connect via your browser to a page on the server that embeds the SWF, Flex ask for the maze data to the server and displays it, and let you navigate using the keyboards or the mouse.
And that's it! So I have a nice, platform independent GUI and functional business code. I was thinking, who needs a special GUI framework for the desktop when an application could be made easily with a very lightweight local HTTP server and a web based interface? I even thought that Flex was a bit too much: why do I need a GUI technology that requires compilation when I can do nice stuff with pure HTML/Javascript frameworks like Dojo? So I can use a UI technology that is purely for UIs, and a functional language with the goodies Haskell provide for all the back-end, computation-heavy work.
The code for Haskell is here (start from Framework.hs), the Flex code is here.

Friday, March 23, 2007

Dynamic class behaviour in Java

In a previous post, I was using annotations to generate method pointers in Java. The functions objects were generated in a separate class file. However, if you suppose that a modern IDE would be able to generate all that code for you when you create a method, you could have the function object in the same class file as the method code itself. Since Java allows you to have a field and a method with the same name, everything works fine.
In that previous post the function object referenced the actual method in the original class file. What if we did the opposite, that is to say, the actual code is in the function object, and the method merely delegates? Here is a trivial example:

public class StringHelperDynamic {

public String toUpper(String a){
return toUpper.run(a);
}

public Function1 toUpper = new Function1 (this){
public java.lang.String run(java.lang.String a) {
return a.toUpperCase();
}
};

}

Here, we have a toUpper method that takes a String and return a String, and a toUpper function object that we can pass around, perform currying on, etc... the interesting twist of this architecture is that the toUpper field can be final or not. If not, we can then change it at runtime, and hence change the behaviour of the class at runtime, while still calling the same methods. Who needs a dynamic scripting language (-: ? To the silly example:

StringHelperDynamic me=new StringHelperDynamic();
me.toUpper=new Function1(me){
public java.lang.String run(java.lang.String a) {
return a.toLowerCase();
}
};

assertEquals("hello",me.toUpper("HELLO"));

OK, breaking the contract of the method is NOT what this is about, but you get the gist of it. The code for the Function1 class can be found here.

Friday, March 16, 2007

VList in Java

Two days ago I was reading this article about LISP like lists implemented in Java,
which reminded me I had written an implementation of a VList in Java. It can be found
here, along with a unit test.I make no garantee this is the best or fastest implementation possible!

It implements: get(n), first (head in Haskell), rest() (tail in Haskell), size(), iterator() and map(Mapper), where Mapper is the mapping interface I mentioned earlier.

It's using Java Generics of course. Am I right in thinking there is no way with Java generics to get rid of the compilation warnings and of the necessity of passing the Class object in the code that creates a new array of the generic type?

Friday, March 09, 2007

Java properties with no language changes (oh no!)


There's been a lot of discussions on the web about Java and the support for bean properties. People would like to have a mechanism that relies less on java bean conventions (reflection on method names, find getters and setters) and more on explicit language constructs. The goal is to simplify bean and property handling, have stronger type checks, be able to reference the property and not its values, etc... Most proposals involve additions to the Java syntax. I don't want to add to the confusion, but I just played around with what we have now in Java 5.
What we could have is instead of defining classes directly with fields in them, we could have them reference Property objects instead. Property objects carry the type information and the value itself. An inheritance hierarchy can provide for read-only, write-only and read-write hierarchy. Using public final fields we can have an access syntax that is not the same as the current getter and setter methods, but pretty close.
Example:

public class PersonBean {
public final IFullProperty name=new NonNullProperty();

public final IReadProperty id;

public final IFullProperty email=new FullProperty(){
@Override
public void set(String value) {
if (value.indexOf('@')==-1){
throw new IllegalArgumentException("email does not contain @");
}
super.set(value);
}
};

public PersonBean(int id,String name){
this.name.set(name);
this.id=new ReadOnlyProperty(id);
}
}

Of course, the generic madness means the type information has to be typed twice, but when generics syntax is cleaned up it'd be a lot more readable. This bean says that it has a changeable name property, a String that cannot be null. It has an id integer property that cannot be changed. Finally it has an email property that has ad hoc constraint checking. The Property interfaces and its sub interfaces define a get() and a set() method so accessing the fields becomes:

bean.getName() -> bean.name.get()
bean.setName(name) -> bean.name.set(name)

The property change listener can be attached to the property object so that the bean doesn't have to have any line of code related to listeners. Everything can be done via static methods:

static void addPropertyChangeListener(Object bean,PropertyChangeListener pcl);

to add a listener on all properties


static void addPropertyChangeListener(Object bean,PropertyChangeListener pcl,IProperty p);

to add a listener on a specific property. Note that since we're taking a property object, and not a property name for example we cannot register a listener on a non existing property. The property does not have a back link to its bean (to avoid disgracious constructors with this), so we need to have both the bean and the propert.
Example:
addPropertyChangeListener(bean,listener,bean.email)

If anybody's interested, all the code with unit tests is available here.




Friday, February 02, 2007

Haskell User Interface???

It's been a long time since I've last posted, the fault to Christmas and holidays. In the meantime though I have done some more Haskell. I have used Prim's algorithms described here to generate a random maze. That forced me to use Random to generate the maze and HGL to display it, and allow the user to navigate from the entrance to the exit with direction keys. Works great, but I was looking at Haskell UIs to see what I could use, and there doesn't seem to be a consensus on a functional GUI library in Haskell. HGL is fairly low level and limited, wxwidgets ports have an imperative air about them and some of the ground breaking frameworks still seem to be experimental (and to be honest, I don't think I'm ready to deal with arrow-based frameworks yet, I'm still struggling with the monads...). So maybe the solution is elsewhere? I've seen in the Java world people talk about Flex, has anybody done anything integrating a Flex front end with a Haskell back-end?

Friday, December 15, 2006

Adventures in Haskell: the Parsec magic weapon

Following suggestions, I have rewritten the parsing code using Parsec. I have to say, it was a good experience. Not everything worked first time, but I feel the code is a lot clearer that doing everything myself line by line. I've compared the two source files: DataAdvParser.hs and the new DataAdvParsec.hs. There's more lines in the Parsec based files because I've had problems with the normal Haskell layout, but the file is overall smaller. Moreover, I have discovered ambiguities and bugs in the initial version when I had to get Parsec to work properly. And of course looking at the Haskell code you actually understand the grammar of the input file...
I don't feel at the moment I'm getting better in Haskell: using Parsec just meant using a library API but didn't mean much in terms of learning the language or the underlying technologies (monads, etc...). I'm thinking maybe writing a little DSL for my adventure game data would help, but I haven't yet found a good tutorial. Ideally I'd like to get to something that's similar to what's been done for HTML or SQL, but for a very simple language...
Anyway, I'll see, next steps would be to write maybe an automated game world generator so that I could play a new game every time...

Friday, December 08, 2006

An infinite list in Java

In Haskell you can define infinite lists by providing, for example, the arithmetical properties of a suite. Lazy evaluation means only the elements needed by the program are calculated. Now, I was looking at doing the same thing in Java, and there's not too much to it.
An infinite list is an Iterable over a generic type (called E in my code). The base class is abstract, and you need to provide the implementation of a getNext() method, that provides the next element in the list. The list is backed by an ArrayList, so that values are only calculated once. There is of course no size() method, but the size of the underlying array list tells you how many elements have been calculated. Note that each calculated value being stored in memory, you cannot go too far in a list with this system. But hey, we're playing here.

For example this is how you can implement the Fibonacci suite, using the code for InfiniteList here:

InfiniteList il=new InfiniteList(){
@Override
protected Integer getNext() {
switch (this.getData().size()){
case 0:return 1;
case 1:return 1;
default: return this.getData().get(this.getData().size()-1)+this.getData().get(this.getData().size()-2);
}
}
};

You then use the iterator() method to get all the results you need. Don't forget to stop at some stages. The getNext() method is called by the calculateNext() method on the base class:

private void calculateNext(){
E next=getNext();
data.add(next);
}

which in turn is called by the ensureCalculated method, that checks that we have the value at a particular index:

private void ensureCalculated(int index){
while (index>=data.size()){
calculateNext();
}
}

So the standard list get method becomes:

public E get(int index) {
if (index<0){
throw new IllegalArgumentException("index<0");
}
ensureCalculated(index);
return data.get(index);
}

You can then have the methods Haskell provide you, for example, take and map. Take returns a sublist made of the nth first elements of the list and map gives back another infinite list calculated from the first by applying a function to each element, as required. We can use the following interface:

public interface Mapper {
E2 map(E1 initial);
}

And the map method is:

public InfiniteList map(final Mapper mapper){
return new InfiniteList(){

@Override
protected E2 getNext() {
return mapper.map(InfiniteList.this.get(getData().size()));
}
};
}

We can also have another infinite list that is a filtered list from the original, using the same interface as above with the E2 generic type a boolean. Watch out, though: if the filter returns false all the time, a call to next() might never return...

The full code can be found here for the InfiniteList class, here for the Mapper interface. Sample code in the form of unit tests are here.

Tuesday, December 05, 2006

Adventures in Haskell: parsing the game world

It's been a while since my last post in Haskell, as it's hard to find the time when I spend 40 hours a week doing Java, and there's little people to take care of in the house... I have been working on my adventure game, still, mainly to separate the data from the actual code. After a fews days of tinkering, I have it working, yoohoo!
Of course, having to write a simple parser was a bit challenging given my limited knowledge of the language, and I wanted to stay with simple constructs. Hence,
I don't use any monadic stuff, I just read the data file and deal with a list of Strings, one String per line, having each method take the list and send back the remainder of list. Promise, I will look into a state monad! And I know there some advanced parsing techniques in Haskell, I mean, more advanced than reading lines and calling words on it...
I had fun with lazy IO, as any newbie Haskell programmer: using getContents seemed sometimes not to give me any lines back, until I understood than evaluating the result after closing the file handle was not the smart way to do things...
So much for the "once it compiles, it works" mantra that I was chanting last time: when parsing a file, the content matters, too, not only the code, so I had trouble solving all the unmatched pattern errors I got. I found GHC more helpful than Hugs for error messages: an error that got me scratching my head for a while in Hugs got solved as soon as I ran the same code in GHC.
I tried as well Hugs.Observe to debug my program, but I fear my grasp of lazy evaluation is too limited yet: sometimes I was sure I was getting into a method but observe was not reporting anything...
Anyway, if anybody is interested in the code, the parser code is here, and an example of a data file is here. The structure is simple enough, blank lines are used a separator and on most lines the first couple of words are keywords (item codes, location codes, etc...). The adapted game code is here (note that the path to the data file is hard-coded here)
As usual, any comments and suggestions welcome!

Friday, November 24, 2006

Higher order functions in Java with an annotation processor factory

I’m continuing my explorations of both Java 5 features like generics and annotations and of functional programming constructs. A lot of Java discussions on the web these days are about closures: writing quick anonymous methods without having to wrap them in a abstract class (think Runnable, Comparator, …). Now, closures can also be related to higher order functions, that is to say functions considered as objects in their own right. If you can reference a precise method inside an instance instead of just having to deal with interface, you can have a type of closures. For example, instead of passing a Comparator object you could pass a Function object, meaning a function that takes two T arguments and returns an integer.
To illustrate this point, let’s take an example.
You have a simple Sale class:

public class Sale {
private String customer;
private Date dateOfSale;
private float amount;

public Sale(String customer, Date dateOfSale, float amount) {
…constructor, getters and setters…

And you have a SaleManager class that encapsulates a list of sales (think retrieved from a database, etc…) and gives you a method to retrieve all sales sorted by what you want:

public class SalesManagerClassic {
private List sales;

public SalesManagerClassic(List sales){
this.sales=sales;
}

public Sale[] listSales(Comparator comp){
Sale[] ret=new Sale[sales.size()];
sales.toArray(ret);
Arrays.sort(ret,comp);
return ret;
}


}

So far so good. Now you define a SaleComparator that will provide you all kinds of comparators:
public class SaleComparatorClassic {

public Comparator compareByCustomer(){
return new Comparator(){
public int compare(Sale o1, Sale o2) {
return o1.getCustomer().compareToIgnoreCase(o2.getCustomer());
}
};
}

public Comparator compareByAmount(){
return new Comparator(){
public int compare(Sale o1, Sale o2) {
return (int) (o2.getAmount()-o1.getAmount());
}
};
}

}

As you can see, creating a comparator each time is tedious. Closure and higher order functions aim at simplifying the important code bits so that the actual strategy (how do we sort the sales) is not buried in all the boilerplate code. This is how we could use that class:

List l=new ArrayList();

SalesManagerClassic smc=new SalesManagerClassic(l);
SaleComparatorClassic scc=new SaleComparatorClassic();
Sale[] s=smc.listSales(scc.compareByCustomer());

A Function object in Java is something like that, roughly:

public abstract class Function {
private Object instance;

public Function(Object instance){
this.instance=instance;
}

public Object getInstance() {
return instance;
}
}

So it encapsulates the instance on which the function will be run. We’re not going out of the OO world right now.
Then generics in Java do not (if they do, drop me a line) allow you to specify that a class can take any number of generic type in its definition, so we’ll have to define a concrete class for all possible numbers of parameters:

public abstract class Function0 extends Function {
public Function0(Object instance){
super(instance);
}

public abstract R run();

}

The code above represents an object method that takes no argument and its return type is the generic type R (which could be Void if the method return nothing). Subclasses need to provide the actual implementation of the run method. And a function taking one parameter will be:

public abstract class Function1 extends Function {

public Function1(Object instance){
super(instance);
}

public abstract R run(P param);

public Function0 curry(final P param){
Function0 f=new Function0(getInstance()){
@Override
public R run() {
return Function1.this.run(param);
}
};
return f;
}

}

Here P is the type of the first parameter. For fun I added the curry function: if you know the first parameter but you don’t want to run the function right now, you can create a Function object with no argument that can be run later.

So what would that mean for our sales manager? This is what the code can look like:

public Sale[] listSales(final Function2 func){
Sale[] ret=new Sale[sales.size()];
sales.toArray(ret);
Arrays.sort(ret,new Comparator(){
public int compare(Sale o1, Sale o2) {
return func.run(o1, o2);
}
});
return ret;
}

The boiler plate for the comparator has been moved in one place (of course we still need it, we’re not writing our own version of Java where standard API calls takes our Function objects right now…). The Sale comparator is where the gain is made:

@FunctionAnnotation
public int compareByCustomer(Sale o1,Sale o2){
return o1.getCustomer().compareToIgnoreCase(o2.getCustomer());
}

@FunctionAnnotation
public int compareByAmount(Sale o1,Sale o2){
return (int) (o2.getAmount()-o1.getAmount());
}

The FunctionAnnotation is a simple method level annotation. This tells us: I want to be able to refer to these methods as Function objects. Note that my code for the moment does NOT deal with methods with the same name and different argument list. We’ll worry about that later… Notice for now how the methods are much simpler and how what they do is clear.

Now, what we need to do, is to do automatically the translation between simple methods with the FunctionAnnotation and Function<…> objects that we can pass to our SalesManager. For this we’ll use an annotation process factory. This factory will run on the source code for SaleComparator, and will generate a SaleComparatorFunctions class that will have methods giving you the Function<…> objects:

public static Function2 compareByAmount(final fr.moresmau.jp.func.samples.SaleComparatorFunctional instance){
return new Function2 (instance){
public Integer run(fr.moresmau.jp.func.samples.Sale param0, fr.moresmau.jp.func.samples.Sale param1) {
return instance.compareByAmount( param0, param1);
}
};
}

public static Function2 compareByCustomer(final fr.moresmau.jp.func.samples.SaleComparatorFunctional instance){
return new Function2 (instance){
public Integer run(fr.moresmau.jp.func.samples.Sale param0, fr.moresmau.jp.func.samples.Sale param1) {
return instance.compareByCustomer( param0, param1);
}
};
}

Aren’t we happy this is generated for us ? Then we can just code our calls like that:
List l=new ArrayList();

SalesManagerFunctional smf=new SalesManagerFunctional(l);
SaleComparatorFunctional h=new SaleComparatorFunctional();
Sale[] s=smf.listSales(SaleComparatorFunctions.compareByCustomer(h));

That code is about the same complexity as before. Of course using another class for the function wrapping make the code not as clear as it should be. In a later post I’ll look at alternatives, so for the moment bear with me.

So we have obtained higher order functions from a standard Java class, and we can use these functions instead of comparator objects.

Now of course I haven’t talked about the annotation process factory yet. There’s nothing magic there. We need to implement an AnnotationProcessFactory and to say we want to do something when we encounter our annotation:

public Collection supportedAnnotationTypes() {
return Arrays.asList("fr.moresmau.jp.func.FunctionAnnotation");
}

And we need to implement a AnnotationProcessor that will generate a Functions class for every class that as at least one method with the FunctionAnnotation. For that we need to use the createSourceFile method of the Filer object provided by the environment to create the function file.
Running the factory is done through the JDK apt tool:

apt -s src -factory fr.moresmau.jp.func.FunctionProcessorFactory -d bin -cp bin src/fr/moresmau/jp/func/samples/SaleComparator.java

The code for the Function objects and the AnnotationProcessFactory can be found here, the Sale example here, with unit tests.

Friday, November 17, 2006

Design By Contract in Java using Annotations, Scripting and Aspects

When you write a Java interface, you define a contract. This contract is made of methods and their signatures. Then, in the implementation code, you can write statements to check that the input parameters are not null, that return values are within a correct range, etc. The problem there of course is that if the implementation doesn't do these checks, or not properly, bugs
may creep in and they may be hard to find. "Design by Contract" is a set of techniques that
let you specify conditions on method parameters, return values, etc, in such a way that they
can be associated with interfaces and that the execution of these statements is assured by the
runtime system, freeing the developer from the tedious tasks of throwing
IllegalArgumentExceptions or assertions.

To implement such techniques, you can use some off the shelf frameworks, like jContractor, but it's easy to roll out your own. You need only three components:
  • you need to be able to attach conditions to classes and methods, without cluttering the code. For this, Java annotations are perfect
  • since we're not in Java code proper, we need a way to run our conditions, so we need a language for them. Well, why have another language, just use a Java scripting languages like Beanshell.
  • finally, the Beanshell code needs to be evaluated at runtime before or after methods calls. This is what aspect are for, right? We'll use AspectJ for that.

So, let's see a concrete example. Suppose we implement a Stack (yeah, right, I don't have a lamer example).
We start with the push method:

public interface IStack {
void push(T o);
}

Ok, but we don't like to have null values in this stack. So we want to specify in the interface definition that the first parameter cannot be null:

@ContractMethodAnnotation (
pre = {"p0!=null"}
)
void push(T o);

We cannot access the names of the method parameters at runtime, so we use a simple convention: p0 is the first parameter, etc. You can also define post conditions that can access the return value using the name "return".

Notice that we specify conditions on the interface, but that we will want the checks to apply to all its implementations.

Conditions can access methods and variables of the class you define them on, but be careful, it's easy to create circular references where two method call each other:

boolean isEmpty();

@ContractMethodAnnotation (
post = {"result>=0"}
)
int size();

It would be tempting to define a condition that isEmpty is true if size()==0 and that size()==0 if isEmpty is true... What you can do is define a class invariant condition: a condition that is always true of an object (even if it can transiently be false, it is true before and after public method invocation).

@ContractClassAnnotation (
invariants={"(isEmpty() && size()==0) || (!isEmpty() && size()>0)"}
)
public interface IStack { ... }

The implementation of the aspect is not very complicated. We define pointcuts for public methods that will check class invariants and for annotated methods that will check pre and post conditions. We use the BeanShell Interpreter object to parse and run the condition code. Thanks to the importObject Beanshell command we can run the code as if all methods referenced by the annotation code referenced the current instance.

When we encounter a failure, we can either use an assertion or throw a RuntimeException.
This can be set through the ContractAspect.setUseAsserts method. For fun, I have defined a way to set it through a bean shell configuration file, that is loaded by another aspect, that executes when the ContractAspect is statically initialized.

The code can be found here: ContractAspect.aj is the aspect implementation, ContractClassAnnotation.java and ContractMethodAnnotation.java are the definition of the annotations. SettingsAspect.aj is the aspect that reads the configuration file and turn assertions on or off. An example of a configuration file is here. As you see, it's only one line of Java code.

The Stack example can be found here, with an implementation and a unit test.


Friday, November 10, 2006

My first Haskell adventure game!

After years of coding mainly in Java, I have taken the plunge and looked
into a pure functional language. Haskell is quite popular these days, so I decided to read a book
on it and play around with it myself.
I got a bit frustrated at the maths or geometry examples, when I got to this great article Casting spels in LISP that uses the medium of a text based adventure game to teach the basic notions of LISP.
So I coded a very little (400 lines with data and documentation) text-based game in Haskell.
The code can be found here (You need a little extra module found here). In my enthusiasm I even added some Haddock documentation here.
The main features are:
- use of the IO monad to get user input and give back feedback
- use of the IO monad to save and load gaves
- use of the Data.Map structure
- use of the Show and Read classes to serialize and deserialize a Map structure
- pure functional handling of state: every change in the game state recreates an instance of the
GameState object. Yes, one day I'll look into the State monad to simplify these functions

My first impressions of Haskell:
- the syntax is quite hard to grasp, with loads of different signs. The indenting drove me mad sometimes.
- thanks for the static typing and the compilation. I found that the hardest part was to get the program to compile.
Once the program compiled all right it usually worked as intended.
- I know that pattern matching and guards are only syntaxic sugar for case statements, but I found them (the patterns, the guards) a lot more elegant and easy to understand
- I need to learn how to deal better with "newtype" and pattern matching. I used "newtype" instead of type for some data types because I needed to declare them as instances of Show and Read, but that forced me to use as-patterns for game state.
Surely there's simpler ways to do that
- yes, I know about $ to avoid parenthesis for function parameters, but with a good editor it's ok to manage

Now, if anybody has tips on how to improve the code I'll take them on board. I'm going to look at separating the data from the code, maybe with a simple DSL and parser. And yes, the state or IORef monads...