Skip to content

Instantly share code, notes, and snippets.

@raymondtay
Created June 26, 2012 02:13
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 raymondtay/2992782 to your computer and use it in GitHub Desktop.
Save raymondtay/2992782 to your computer and use it in GitHub Desktop.
novice trying out type level prog
val rubbishFn =new { type Pred = Int => Boolean; type MA[Pred] = List[Pred]; def test(colFn: MA[Pred])(implicit e: MA[Pred] <:< List[Pred]) = for(fn <- colFn) println(fn(1)) }
scala> def bind[A,B,C](a: A, p: A => B, f: (B, A) => C): C = f(p(a),a)
bind: [A, B, C](a: A, p: A => B, f: (B, A) => C)C
scala> def applyIf[A](a: A, f: A=>A, p: A => Boolean) : A = { val res = p(a); bind(a, p, (res:Boolean,a:A) => res match { case true => f(a); case _ => a} )}
applyIf: [A](a: A, f: A => A, p: A => Boolean)A
def sqrt(n : Double) : Double = {
def f(x : Double) = (x * x ) - n
iterateWhile(2.0)(x => x - f(x) / (2 * x), x => f(x).abs > 1e-14)
}
type Pred[A] = A => Boolean
def iterateWhile[A](a: A )(f: A => A , p: Pred[A]) : A = {
val r = Iterator.continually {
if (p(a)) f(a) match { case e if e == a => e; case e1 => e1 } } takeWhile(_ != a); r.next.asInstanceOf[A] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment