Skip to content

Instantly share code, notes, and snippets.

@yellowflash
Created January 4, 2017 10:28
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 yellowflash/361c6e31d5f2323f603b5fb5e02404df to your computer and use it in GitHub Desktop.
Save yellowflash/361c6e31d5f2323f603b5fb5e02404df to your computer and use it in GitHub Desktop.
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