Skip to content

Instantly share code, notes, and snippets.

@milessabin
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milessabin/8820772 to your computer and use it in GitHub Desktop.
Save milessabin/8820772 to your computer and use it in GitHub Desktop.
Using type classes indexed by the singleton types of function values to statically verify interesting properties. Obviously this relies on the instance declaration telling the truth but, given that, it is nevertheless checkable at use sites.
scala> trait Pure[T]
defined trait Pure
scala> val plusOne: Int => Int = _ + 1
plusOne: Int => Int = <function1>
scala> val frobPlusOne: Int => Int = { i => println("frob") ; i + 1 }
frobPlusOne: Int => Int = <function1>
scala> implicit val plusOneIsPure = new Pure[plusOne.type]{}
plusOneIsPure: Pure[plusOne.type] = $anon$1@20b8610d
scala> def map[A, B](l: List[A], f: A => B)(implicit fIsPure: Pure[f.type]) = l map f
map: [A, B](l: List[A], f: A => B)(implicit fIsPure: Pure[f.type])List[B]
scala> map(List(1, 2, 3), plusOne)
res0: List[Int] = List(2, 3, 4)
scala> map(List(1, 2, 3), frobPlusOne)
<console>:13: error: could not find implicit value for parameter fIsPure: Pure[frobPlusOne.type]
map(List(1, 2, 3), frobPlusOne)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment