Skip to content

Instantly share code, notes, and snippets.

@machuz
Created January 2, 2016 14:13
Show Gist options
  • Save machuz/7cf23ad4fae04c5a1eab to your computer and use it in GitHub Desktop.
Save machuz/7cf23ad4fae04c5a1eab to your computer and use it in GitHub Desktop.
FP in scala 勉強メモ [PartⅠ 第2章 Scala関数型プログラミングの準備] ref: http://qiita.com/ma2k8/items/9ecbf03d6a07d79868f4
// Q
n番目のフィボナッチ数を取得する再帰関数を記述せよ。
// answer
def fib(n: Int): Int = {
@annotation.tailrec
def loop(v: (Int,Int), count: Int): Int = {
val (x, y) = v
if (n > count) loop((y,x+y),count+1)
else x
}
loop((0, 0+1), 0)
}
// 公式のanswer
def fib(n: Int): Int = {
@annotation.tailrec
def loop(n: (Int,Int), max: Int): Int = {
val (x,y) = n
if (max <= 0) x
else loop((y,x+y),max-1)
}
loop((0,1),n)
}
// Q
指定された比較関数に従ってArray[A]がソートされているかどうか調べるisSortedを実装せよ。
// answer
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean) = {
@annotation.tailrec
def loop(ar: Seq[A]): Boolean = {
ar match {
case Seq(x ,y, vs@_*) =>
if (ordered(x,y)) loop(y +: vs)
else false
case _ => true
}
}
loop(as.toSeq)
}
// 公式のanswer
def isSorted[A](as: Array[A], ordered:(A,A) => Boolean): Boolean = {
@annotation.tailrec
def loop(n: Seq[A]): Boolean = {
n match {
case Seq(x, y, vs@_*) =>
if (ordered(x, y)) loop(y +: vs)
else false
case _ => true
}
}
loop(as.toSeq)
}
// 実行
isSorted[Int](Array(1,2,3), (x:Int,y:Int) => if (x < y) true else false)
// Q
カリー化(currying)では、引数2つの関数fが、fを部分的に適用する引数1つの関数に変換される。
この場合も、コンパイルできる実装は1つだけである。この実装を記述せよ。
// answer
def curry[A,B,C](f: (A,B) => C): A => (B => C) = (a: A) => (b: B) => f(a, b)
// 公式のanswer
def curry[A,B,C](f: (A,B) => C): A => (B => C) = (a: A) => ((b: B) => f(a,b))
// Q
uncurryを実装せよ。
// answer
def uncurry[A,B,C](f: A => B => C): (A,B) => C = (a: A, b: B) => f(a)(b)
// 公式のanswer
def uncurry[A,B,C](f: A => B => C): (A,B) => C = (a: A,b: B) => f(a)(b)
// Q
2つの関数を合成する高階関数を実装せよ。
// answer
def compose[A,B,C](f: B => C, g: A => B): A => C = (a: A) => f(g(a))
// 公式のanswer
def compose[A,B,C](f: B => C, g: A => B): A => C = (a: A) => f(g(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment