From 17b5c3adebd1f94c4af96fb2ac309a04e9cd57f3 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 25 Feb 2025 13:52:14 +0100 Subject: [PATCH] added assignment 2 ex 1 --- src/Assignment1/SquareRoot.sc | 2 +- src/Assignment2/Ex1.sc | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 src/Assignment2/Ex1.sc diff --git a/src/Assignment1/SquareRoot.sc b/src/Assignment1/SquareRoot.sc index 6053d88..65994f2 100644 --- a/src/Assignment1/SquareRoot.sc +++ b/src/Assignment1/SquareRoot.sc @@ -15,4 +15,4 @@ def sqrt(x: Double, approx: Double): Double = if ( sqrt(x, improve(x, approx)) } -sqrt(612, 10) \ No newline at end of file +sqrt(612, 10) diff --git a/src/Assignment2/Ex1.sc b/src/Assignment2/Ex1.sc new file mode 100644 index 0000000..c8415ff --- /dev/null +++ b/src/Assignment2/Ex1.sc @@ -0,0 +1,17 @@ +import scala.annotation.tailrec + +def fib(x: Int): Int = if (x == 0 || x == 1) {x} else { + fib(x - 1) + fib(x - 2) +} + +def fibTail(x: Int): Int = { + @tailrec + def fibTailStep(x: Int, a: Int, b: Int): Int = { + if (x == 0) {a} + else fibTailStep(x - 1, b, a + b) + } + fibTailStep(x, 0, 1) +} + +fib(10) +fibTail(10) \ No newline at end of file