Skip to content

Instantly share code, notes, and snippets.

@sambaiz
Created July 3, 2015 09:52
Show Gist options
  • Save sambaiz/fe0c2b3079b491029222 to your computer and use it in GitHub Desktop.
Save sambaiz/fe0c2b3079b491029222 to your computer and use it in GitHub Desktop.
Scala関数型デザイン&プログラミング2章
/*
EXERCISE 2.1
n番目のフィボナッチ数を取得する再帰関数を記述せよ
再帰関数ではローカルな末尾再帰関数を使用する
(
*/
object Fibonacci{
def fib(n: Int): Int = {
@annotation.tailrec
def go(n: Int, acc: Int, before: Int): Int =
if(n <= 1) acc
else go(n-1, acc+before, acc)
go(n, 0, 1)
}
def main(args: Array[String]): Unit = {
for(i <- 1 to 10)
println(fib(i))
}
}
/*
EXERCISE 2.2
指定された比較関数に従ってArray[A]がソートされているかどうかを調べる
isSortedを実装せよ
*/
object IsSorted{
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean): Boolean = {
def go(arr: Array[A], i:Int): Boolean = {
if(i >= arr.length - 1)
true
else if(ordered(arr(i),arr(i+1)))
go(arr, i+1)
else
false
}
go(as, 0)
}
def main(args: Array[String]): Unit = {
val arr = Array(0, 1, 2, 3, 4, 5)
val ordered = (x: Int, y: Int) => x < y
println(isSorted(arr, ordered))
val ordered2 = (x: Int, y: Int) => x > y
println(isSorted(arr, ordered2))
}
}
/*
EXERCISE 2.3
カリー化の実装
*/
object Currying {
def curry[A,B,C](f: (A, B) => C): A => (B => C) =
(a: A) => ((b: B) => f(a, b))
def main(args: Array[String]) = {
val one_plus = curry((x: Int, y: Int) => x + y)(1)
println(one_plus(10))
}
}
/* EXERCISE 2.4
カリー化の逆向き
*/
object UnCurrying{
def uncurry[A,B,C](f: A => (B => C)): (A, B) => C =
(a: A, b: B) => f(a)(b)
def main(args: Array[String]) = {
val plus = uncurry((x: Int) => ((y: Int) => x + y))
println(plus(1, 10))
}
}
/*
EXERCISE 2.5
2つの関数を合成する高階関数を実装せよ
*/
object Compose {
def compose[A, B, C](f: B => C, g: A => B): A => C =
(a: A) => f(g(a))
def main(args: Array[String]) = {
val f = (n: Int) => n + 2
val g = (n: Int) => n * 2
println(compose(f, g)(2))
println((f compose g)(2)) // 標準ライブラリで定義されている
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment