Commit 0c18d71e authored by Haochen Xie's avatar Haochen Xie

add ch2/GetStartedFP.scala

parent 072b4b4d
package name.haochenxie.fpscala.ch2
import scala.annotation.tailrec
object GetSartedFPScratch {
// Exercise 2.1
def fib(n: Int): Int = {
@tailrec
def rec(iter: Int, a: Int, b: Int): Int =
if (iter == n) a
else rec(iter + 1, b, a + b)
rec(0, 0, 1)
}
// Exercise 2.2
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
def rec(n: Int, len: Int): Boolean = {
if (n < len-1) {
if (ordered(as(n), as(n+1))) return rec(n+1, len)
else false
} else {
return true
}
}
rec(0, as.length)
}
// Exercise 2.3
def curry[A,B,C](f: (A, B) => C): A => (B => C) = x => y => f(x, y)
// Exercise 2.4
def uncurry[A,B,C](f: A => (B => C)): (A, B) => C = { case (x, y) => f(x)(y) }
// Exercise 2.5
def compose[A,B,C](f: B => C, g: A => B): A => C = x => f(g(x))
def main(args: Array[String]) {
println("\n-------------")
println("Exercise 2.1:")
println(List.range(0, 10).map(fib))
println("\n-------------")
println("Exercise 2.2:")
println(isSorted[Int](Array(), { case (a, b) => a < b }))
println(isSorted[Int](Array(1), { case (a, b) => a < b }))
println(isSorted[Int](Array(1, 2), { case (a, b) => a < b }))
println(isSorted[Int](Array(1, 3, 2), { case (a, b) => a < b }))
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment