Created
March 4, 2014 12:10
-
-
Save ceedubs/9345388 to your computer and use it in GitHub Desktop.
Using Scala type tags to ensure that a String is lower case. At compile time we can require a String @@ LowerCase (that is, a String that we are promising is lower case). However at runtime there is no extra boxing, so we don't have the overhead we would have if we wrapped strings in a LowerCase class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scala> import scalaz.{ @@, Tag } | |
import scalaz.{$at$at, Tag} | |
scala> sealed trait LowerCase | |
defined trait LowerCase | |
// as an optimization you could also define a TrustMeLowerCase method that doesn't call toLowerCase if you know your input is already lower case | |
scala> def LowerCase(s: String): String @@ LowerCase = Tag[String, LowerCase](s.toLowerCase) | |
LowerCase: (s: String)scalaz.@@[String,LowerCase] | |
scala> val canonicalConcepts: Map[String @@ LowerCase, String] = Map(LowerCase("United States of America") -> "Murica") | |
canonicalConcepts: Map[scalaz.@@[String,LowerCase],String] = Map(united states of america -> Murica) | |
scala> canonicalConcepts.get("United States of America") | |
<console>:12: error: type mismatch; | |
found : String("United States of America") | |
required: scalaz.@@[String,LowerCase] | |
(which expands to) String with AnyRef{type Tag = LowerCase} | |
canonicalConcepts.get("United States of America") | |
^ | |
scala> canonicalConcepts.get(LowerCase("United States of America")) | |
res1: Option[String] = Some(Murica) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment