FunkyJFunctional icon indicating copy to clipboard operation
FunkyJFunctional copied to clipboard

Pattern matching in java

Open pyricau opened this issue 13 years ago • 2 comments

I just read this article : http://kerflyn.wordpress.com/2012/05/09/towards-pattern-matching-in-java/

Looks like there's something for FunkyJFunction here :) .

Improvisation based on one of the examples :


public static int funky_fact(final int n) {

    class Zero extends Func<Integer, Object> {{ out = 0; }}

    class Otherwise extends Func<Object, Object> {{ out = in* fact(in - 1); }}

    return ((Integer) new PatternMatching(
            inCaseOf(0, Zero.class),
            otherwise(Otherwise.class)
    ).matchFor(n));
}

This is just a general idea, I think we could do better regarding generics (basically PatternMatching could have two params, one for the input type and one for the output type.

pyricau avatar May 12 '12 13:05 pyricau

Maybe a better example (needs to be checked) :



    class IsInteger extends Func<Integer, String> {{ out = "Integer: " + in; }}

    class IsWorld extends Func<String, String> {{ out = "hello " + in; }}

    class Is42 extends Func<Integer, String> {{ out = "forty-two"; }}

    class Otherwise extends Func<Object, String> {{ out = "got this object: " + x; }}


PatternMatching<String> pattern = pattern(
    inCaseOf(Integer.class, IsInteger.class),
    inCaseOf("world", IsWorld.class),
    inCaseOf(42, Is42.class),
    otherwise(Otherwise.class)
);


String result1 = pattern.match(42);
String result2 = pattern.match("world");

pyricau avatar May 12 '12 13:05 pyricau

See also here : https://gist.github.com/2658827

pyricau avatar May 12 '12 13:05 pyricau