Skip to content

Instantly share code, notes, and snippets.

@erikkaplun
Last active August 29, 2015 14:07
Show Gist options
  • Save erikkaplun/2a4a00bc47b2a53aeae6 to your computer and use it in GitHub Desktop.
Save erikkaplun/2a4a00bc47b2a53aeae6 to your computer and use it in GitHub Desktop.
package prob
import scalaz._
import Scalaz._
import org.scalacheck.{ Arbitrary, Gen }
/** Types for working with probabilities, i.e. values of type `Double` in range `[0.0, 1.0]`. */
object `package` {
/** a value that contains a probability.
*
* See http://eed3si9n.com/learning-scalaz/Tagged+type.html for a tutorial.
*/
sealed trait Probability
private val Probability = Tag.of[Probability]
/** tag a `Double` within `[0.0, 1.0]` with `Probability` */
val P = (x: Double) => {
require(0.0 <= x && x <= 1.0)
Probability(x)
}
/** a `Double` that contains a probability value */
type P = Double @@ Probability
/** convert a `P` back to its underlying `Double` */
val `P->Double` = Probability.unwrap(_: P)
/** `Arbitrary[P]` for ScalaCheck */
implicit val ArbitraryP = Arbitrary(Gen.choose(0.0, 1.0).map(P(_)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment