Skip to content

Instantly share code, notes, and snippets.

@cshtdd
Last active August 11, 2016 11:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cshtdd/718451d75e4b0fd3325a to your computer and use it in GitHub Desktop.
Save cshtdd/718451d75e4b0fd3325a to your computer and use it in GitHub Desktop.
scala-unstable-identifiers
//paste the contents of this file on a scala console and inspect the results
abstract class Token
case class TNum(n: Double) extends Token
case class TOpenP() extends Token
case class TCloseP() extends Token
case class TSum() extends Token
case class TDiff() extends Token
case class TMult() extends Token
case class TDiv() extends Token
case class TNeg() extends Token
val priorities = List(
(0, TSum()),
(0, TDiff()),
(1, TMult()),
(1, TDiv()),
(1, TNeg()),
(3, TOpenP())
)
//prints one
priorities.collectFirst({ case (x, TMult()) => x }).get
val op: Token = TMult()
//prints zero... waat!!
priorities.collectFirst({ case (x, op) => x }).get
//this solves the issue, but it is not idiomatic enough, it looks kind of ugly
priorities.collectFirst({ case (x, y) if y == op => x }).get
//and this too prints one, this is the idiomatic solution, it is called stable identifier
priorities.collectFirst({ case (x, `op`) => x }).get
//this also prints one, this is another way for referencing a stable identifier
val Op: Token = TMult()
priorities.collectFirst({ case (x, Op) => x }).get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment