Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package cont
import scala.util.Try
abstract class Cont[A] {
def run[R](cont: A => R): R
def map[B](fn: A => B): Cont[B] = {
val self = this
new Cont[B] {def run[R](cont: B => R) = self.run(cont compose fn)}
}
def flatMap[B](fn: A => Cont[B]): Cont[B] = {
val self = this
new Cont[B] {def run[R](cont: B => R) = self.run(a => fn(a).run(cont))}
}
def get = run(identity)
}
object Constraint {
def choose[A](as: A*):Cont[A] = new Cont[A] {
override def run[R](cont: A => R): R = {
doChoose(cont, as.toList)
}
def doChoose[R](cont: A => R, values: List[A]):R = {
if(values.isEmpty) throw new RuntimeException("No choice is valid")
Try(cont(values.head)).getOrElse(doChoose(cont, values.tail))
}
}
def check(bool: => Boolean): Unit = {
if(!bool) throw new RuntimeException("Constraint fails")
}
}
object PythagoreanTriples {
import Constraint._
def main(args: Array[String]) = {
println((for(
a <- choose(1,2,3,4,5);
b <- choose(1,2,3,4,5);
c <- choose(1,2,3,4,5)
) yield {
check(a > b)
check((a*a + b*b) == c*c)
(a,b,c)
}).get)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment