From 9d3d394aeb7a74da6b15fbcc3f3c92f7e23ed1b1 Mon Sep 17 00:00:00 2001 From: Matthieu Bovel <matthieu.bovel@epfl.ch> Date: Tue, 12 Oct 2021 12:58:52 +0200 Subject: [PATCH] Add fixedPoint curry version See https://gitlab.epfl.ch/lamp/cs210/-/issues/63 --- exercises/solution-02.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/exercises/solution-02.md b/exercises/solution-02.md index 75ee2b7..ae23e9a 100644 --- a/exercises/solution-02.md +++ b/exercises/solution-02.md @@ -59,10 +59,18 @@ import scala.annotation.tailrec def fixedPoint(f: Int => Int): Int => Int = @tailrec - def rec(x: Int): Int = - val y = f(x) - if x == y then x else rec(y) - rec + def loop(guess: Int): Int = + val image: Int = f(guess) + if image == guess then guess else loop(image) + loop +``` + +Or alternatively, using currying: + +```scala +def fixedPointCurry(f: Int => Int)(guess: Int): Int = + val image: Int = f(guess) + if image == guess then guess else fixedPoint(f)(image) ``` - `fixedPoint(x => x/2)(4)` returns `0`. -- GitLab