0

If you have these Haskell data types

data Mlist a = Mlist [a]

data Mordering = MLT | MEQ | MGT | MIN deriving (Eq, Show)

Whats the best way to write this in java?

2
  • What's wrong with Java's existing list data type? As for the latter, I don't really know Java, but it must have enumerations of some kind... Commented Mar 16, 2013 at 19:07
  • Maybe you can have a look at jamesiry.github.com/jADT/index.html Commented Mar 16, 2013 at 20:28

2 Answers 2

8

If you want to get sum-only type in Java, then it is easy. Just use enum:

public enum Mordering {
    MLT, MEQ, MGT, MIN
}

You even get equality, toString() and other useful things for free. If you need product-only type, like your Mlist, then simple class is the way to go:

public class Mlist<T> {
    public final List<T> list;

    public Mlist(List<T> list) {
        this.list = list;
    }
}

If you need full ADT (sum of products) though, then things may get more complex.

Usually such types are encoded using inheritance. Consider Guava Optional class. It is equivalent to Haskell Maybe datatype. It is modelled as a base class, called Optional, and two subclasses: Present, which maps to Haskell Just, and Absent, which maps to Nothing. Also base class, Optional, contains some useful factory methods, like Optional.of(value) or Optional.absent(). I think this is the approach you should use.

However, the value of ADTs without pattern matching quickly diminishes. I think you'd better not try to use Haskell idioms in Java, since these are completely different languages, each having its own set of patterns and techniques. Some of the general concepts may be useful in both of them (like Optional/Maybe), but usually there are completely different approaches to problems in these languages.

BTW, Scala language (also runs on JVM) models ADTs in similar fashion, usually using abstract sealed base class and multiple case classes extending it:

abstract sealed class Optional[+T]
case class Present[+T](value: T) extends Optional[T]
case class Absent() extends Optional[Nothing]
Sign up to request clarification or add additional context in comments.

Comments

2

Not sure if there is a best way to do it.

But to get an idea, one could do the following: Run this code through the frege compiler and look at the java code it generates.

(Frege is a JVM language that tries to make up for the missing Haskell-JVM backend. Frege is essentially Haskell 2010 plus higher ranked polymorphic types and Java interop.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.