0

I'm just starting to use the FunctionalJava library and wanted to make use of the immutable TreeMap. However I can't figure out how to create an empty one to start with when using a user defined class or interface.

fj.data.TreeMap<IAddress, Optional<ScanNode>> nodes = TreeMap.empty(Ord<IAddress>);

All the examples use predefined types like Ord.stringOrd. I'm totally not understanding how to create the proper Ord<IAddress>.

Could someone explain how to do this?

Thanks, Derek

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
Derek Ealy
  • 235
  • 1
  • 8

2 Answers2

3

Essentially a tree-map has to have some sort of an ordering on its elements, so you must describe how to order your IAddress.

for example, lets say IAddress has 2 strings and an int (city, street, number), you could do the following:

// translate an IAddress to a P3 containing the important data
F<IAddress, P3<String, String, Integer>> toP3 = new F<...> () {
        P3<String, String, Integer> f(IAddress addr) { 
              return P.p(addr.getCity(), addr.getStreet(), addr.getNumber());
}

main () {
    // first map IAddress to a P3 using the function above, then simply order it by its fields
    Ord<IAddress> addrOrd = Ord.P3Ord(Ord.StringOrd, Ord.StringOrd, Ord.IntOrd).comap(toP3);

    fj.data.TreeMap<IAddress, Optional<ScanNode>> nodes = TreeMap.empty(addrOrd);
}

co-mapping means it first applies the function toP3 on the IAddress, getting back the P3, and then ordering it with the given P3 order.

Shlomi
  • 4,708
  • 1
  • 23
  • 32
  • of course, if you dont really mind about the ordering, you could always use something like Ord.hashOrd() or Ord.hashEqualsOrd() – Shlomi Jul 18 '12 at 07:40
  • Wow, that's pretty ugly to look at. I didn't see any mention of hashOrd() or hashEqualsOrd() in the docs. They're probably sufficient for my needs. – Derek Ealy Jul 18 '12 at 15:58
  • 1
    TreeMap is mostly useful because it gives you ordered iteration of the data. If you don't need that, you might be better off using HashMap – ron Jul 26 '12 at 12:32
0

If IAddress implements Comparable, you can also use Ord.<IAddress>comparableOrd() to construct an Ord for it.

Dobes Vandermeer
  • 8,463
  • 5
  • 43
  • 46