From 2856c814c6af135dda2e7d02f1f7d2ddb0598e68 Mon Sep 17 00:00:00 2001 From: Julien Lengrand-Lambert Date: Wed, 24 Oct 2018 16:26:45 +0200 Subject: [PATCH] Start functional programming in Scala book --- build.sbt | 5 +++++ src/main/scala/myModule.scala | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 build.sbt create mode 100644 src/main/scala/myModule.scala diff --git a/build.sbt b/build.sbt new file mode 100644 index 0000000..c1be089 --- /dev/null +++ b/build.sbt @@ -0,0 +1,5 @@ +name := "functional-programming-scala" + +version := "0.1" + +scalaVersion := "2.12.7" \ No newline at end of file diff --git a/src/main/scala/myModule.scala b/src/main/scala/myModule.scala new file mode 100644 index 0000000..5f9d0ee --- /dev/null +++ b/src/main/scala/myModule.scala @@ -0,0 +1,33 @@ +object myModule { + def abs(n: Int): Int = + if (n < 0) -n else n + + def factorial(n: Int): Int = { + + def fact(n: Int, acc: Int) : Int = { + if(n == 1) acc + else fact(n - 1, acc * n) + } + + fact(n, 1) + } + + def fibonacci(n: Int) : Int = { + def go(n:Int, prev:Int, curr: Int): Int = { + if(n == 0) prev + else + go(n-1, curr, prev + curr ) + } + + go(n, 0, 1) + } + + private def formatAbs(x: Int) ={ + val msg = "The absolute value of %d is %d" + msg.format(x, abs(x)) + } + + def main(args: Array[String]): Unit ={ + println(formatAbs(-42)) + } +}