Building Generate Binary

Note: if you somehow got to this page out of context, it is an old version of one section of this article.


Another use of the merge is a simple shuffle. The basic idea is that we're going to choose between the two lists at random. First, we need some way to generate a coin flip. In normal java, the code we'd want is the boolean expression:

Math.random() <= 0.5d

There are three elements here: Math.random (a generator), the constant value, and the less than comparison. To get this into functor form, we start by building a LessEqual binary functor. We need to bind the second argument of the functor to the constant value 0.5d. Then, we want to hook the first argument of the functor to a generator that produces random numbers. The result looks like this:

Generator<Double> coinflip = 
    new LessEqual<Double>().bind2nd(0.5d).generate(new Random());

The next problem is that the merge operation is going to try and pass two arguments to our Generator. Generator by definition doesn't support taking arguments, so we need to allow our coin flip to receive two arguments, even though they will be ignored. To do this, we'll need to use one of the Adaptors. Normally, we don't need to resort to using the functors in the Adaptor package directly: they all have methods in the UnaryFunctor and BinaryFunctor classes that hide them away. This time, however, there isn't (in this release) an appropriate adaptor, so we'll toss one together real quick.

import net.sf.jga.fn.BinaryFunctor;
import net.sf.jga.fn.Generator;

public class GenerateBinary<T1,T2,R> extends BinaryFunctor<T1,T2,R> {
    private Generator<R> _gen;
    public GenerateBinary(Generator<R> gen) { _gen = gen; }
    public R fn(T1 arg1, T2 arg2) { return _gen.gen(); }

So now, we can use the following as the functor passed to a merge operation to implement a simple shuffle.

BinaryFunctor<Fruit,Fruit,Boolean> shuffle = 
        new GenerateBinary<Fruit,Fruit,Boolean>(coinflip);

for(Fruit f : merge(yellow, unique(citrus), shuffle)) {

Shuffled Fruits