Skip to content

Commit

Permalink
ackerman
Browse files Browse the repository at this point in the history
  • Loading branch information
Guillaume Masse authored and Guillaume Masse committed Feb 6, 2015
1 parent 58f785d commit ffc544b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
13 changes: 12 additions & 1 deletion ttfi-core/src/main/scala/TTFI.scala
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ object TTFI {
object OpenRecursion {
import scala.annotation.tailrec

// not tail-recursive
// not @tailrec
def fix[A, B](f: (A => B) => (A => B)): A => B = {
f((x: A) => fix(f)(x))
}
Expand All @@ -368,6 +368,17 @@ object TTFI {
}
}

// http://rosettacode.org/wiki/Y_combinator#Scala
object Fix2 {
def apply[A, B](f: (A => B) => (A => B)) = {
case class W(wf: W => A => B) {
def apply(w: W) = wf(w)
}
val g: W => A => B = w => f(w(w))(_)
g(W(g))
}
}

// {{{ FixCurried

object FixCurried {
Expand Down
21 changes: 21 additions & 0 deletions ttfi-core/src/test/scala/FixSpecs.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import TTFI._

import org.specs2._
class Fix_Spec extends Specification {
def is = s2"""
Fix should not blow the stack $stackSafe
"""

def stackSafe = {

// en.wikipedia.org/wiki/Ackermann_function
def acktabs(ack: ((Int, Int)) => Int)(in: ((Int, Int))): Int = {
val (m, n) = in
if (m <= 0) n + 1
else if (n <= 0) ack((m - 1, 1))
else ack((m - 1, ack((m, n - 1))))
}

Final.TreeSem.OpenRecursion.fix(acktabs)((5, 5)) ==== 0
}
}

0 comments on commit ffc544b

Please sign in to comment.