scala - Case object enumerations, order and implicits -


for pedagogical purposes have implemented enumeration using both enumeration , case objects. i'm comfortable enumeration version, although cannot warn of missing cases in match statement.

i have tried write equivalent using case objects finding that, although compiles, doesn't run. in particular, seems go infinite loop @ run time (i haven't been able confirm in debugger, however). here's code i'm trying run:

sealed abstract class suit extends ordered[suit] {   val name: string   val priority: int   override def tostring = name   def compare(that: suit) = priority-that.priority } case object spades extends suit { val name = "spades"; val priority = 0 } case object hearts extends suit { val name = "hearts"; val priority = 1 } case object diamonds extends suit { val name = "diamonds"; val priority = 2 } case object clubs extends suit { val name = "clubs"; val priority = 3 }  object suit {   implicit def ordering[a <: suit]: ordering[a] = suit.ordering   def suits = list(clubs,spades).sorted } 

if enter code repl (via paste mode) or if compile in eclipse, appears well. if try test suits method of suit object, run hangs , have terminate it.

i have tried if not of suggestions i've found here on stackoverflow regarding implicits (for instance, not defining suit class extend ordered[suit] , instead specifying ordering directly class. none of these have compiled however.

working suggestions appreciated.

object suit {   implicit def ordering[a <: suit]: ordering[a] = suit.ordering } 

that infinite loop, ordering calls itself. think want ordering[suit], doesn't make sense in case ask ordering of sub-type a of suit (that 1 individual case object).

there implicit ordering types extend ordered, won't need construct one:

implicitly[ordering[suit]]  // aka ordering.ordered[suit] 

so following works:

object suit {   def suits = list[suit](clubs, spades).sorted } 

note list(clubs, spades).sorted won't work, because inferred list element type suit product , somehow produces failure find unambiguous ordering.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -