Automatically generated print order / ADT in Scala

Is it possible to automatically deduce the order in the family of closed qualities in Scala?

For example, it would be nice to be able to:

sealed trait Letters case object A extends Letters case object B extends Letters (A < B) == True 

This is similar to what Shapeless can handle, but I don’t see if this currently exists.

+5
source share
2 answers

I assume that you want the ordering to reflect the order of definition, rather than being ordered by constructor names.

This is not as fun as you might expect, because the knownDirectSubclasses in the ClassSymbol API returns a character set, not an ordered sequence. I am not an expert on internal characteristics, but according to Eugene Burmako (who is), the signature of knownDirectSubclasses simply reflects what is happening in scalac.

I have been complaining about this for many years, by the way, and at different points I have tried things like reading positions from characters , but actually it does not work.

Here a decision should be made on a helpless generic mechanism, since it represents sealed traits as co-products that organize their elements. To determine things, it uses the names of the constructors to organize cases:

 // Entering paste mode (ctrl-D to finish) sealed trait Letters case object B extends Letters case object A extends Letters // Exiting paste mode, now interpreting. defined trait Letters defined object B defined object A scala> shapeless.Generic[Letters] res5: shapeless.Generic[Letters]{type Repr = shapeless.:+:[A.type,shapeless.:+:[B.type,shapeless.CNil]]} = anon$macro$45$1@71a11be4 

If this is what you want, you are all set up - just find a good tutorial on generic generation without using Shapeless and work out the details. Unfortunately, in most cases this is probably not what you want ( East , North , South , West ? Blue , Green , Red ?) And what you want (ordering) does not seem to be reasonably possible .

+5
source

When writing Enumeratum, I came to the same conclusion as Travis that knownDirectSubclasses could not provide information about the announcement of the order.

Nevertheless, although inside the body of this module AST is still ordered (type List[Tree] ), since I managed to make a declaration based on orders and offer the indexOf method. If you have an ordered sequence of sealed attribute instances, getting Order pretty trivial.

Sorry, this is not a shameless answer.

0
source

Source: https://habr.com/ru/post/1246056/


All Articles