Skip to content

Instantly share code, notes, and snippets.

@larsrh
Created November 17, 2013 21:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsrh/7518710 to your computer and use it in GitHub Desktop.
Save larsrh/7518710 to your computer and use it in GitHub Desktop.
Code examples from scala.io 2013 (see comments). Note that until shapeless 2.0.0 is out, this is still in a state of flux.
scalaVersion := "2.10.2"
resolvers += Resolver.sonatypeRepo("snapshots")
libraryDependencies += "org.typelevel" %% "shapeless-scalaz" % "0.2-SNAPSHOT"
libraryDependencies += "org.typelevel" %% "shapeless-scalacheck" % "0.2-SNAPSHOT"
initialCommands in console := """
import scalaz._
import scalaz.std.anyVal._
import scalaz.std.option._
import scalaz.std.string._
import shapeless._
import shapeless.contrib.scalaz._
import shapeless.contrib.scalacheck._
"""
case class Employee(name: String, years: Int, salary: Float)
sealed trait Shape
case class Circle(radius: Int) extends Shape
case class Rectangle(height: Int, width: Int) extends Shape
@larsrh
Copy link
Author

larsrh commented Nov 17, 2013

Start sbt, open up a console, and try these:

val grace = Employee("Grace Hopper", 20, 60000f)
val olderGrace = Employee("Grace Hopper", 30, 70000f)

Order[Employee]
Order[Employee].order(grace, olderGrace)

import scalaz.syntax.order._
grace < olderGrace

@larsrh
Copy link
Author

larsrh commented Nov 17, 2013

More examples:

val circle: Shape = Circle(30)
val rect: Shape = Rectangle(10, 20)

import shapeless.contrib.scalaz.Binary.auto._
import shapeless.contrib.scalaz.binary._

circle.encode.decode[Shape]
List(circle, rect).encode.decode[List[Shape]]

import scalaz.syntax.equal._

circle === rect
rect === rect

@larsrh
Copy link
Author

larsrh commented Nov 17, 2013

And, if you want to check that serialization is actually lawful:

import org.scalacheck.Prop
import shapeless.contrib.scalaz.Binary.auto._
import shapeless.contrib.scalaz.binary._

val prop = Prop.forAll { (s: Shape, rest: List[Byte]) => (s.encode ++ rest).decode[Shape] == Some((s, rest.toVector)) }

prop.check
// + OK, passed 100 tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment