ababup1192
11/15/2016 - 9:44 AM

## 非関数型プログラマでも分かる関数型プログラミング入門 ref: http://qiita.com/ababup1192/items/3429c1e9cf7eabf55d9c

``````def length(list: List[Int]): Int =
list match {
case Nil     => 0
case x :: xs => 1 + length(xs)
}

println(length(List(18, 29, 36, 12, 15)))
// => 5
``````
``````Main.scala:5: warning: match may not be exhaustive.
It would fail on the following input: Nil
list match {
^
one warning found
``````
``````def sum(list: List[Int]): Int =
list match {
case x :: xs => x + sum(xs)
}
``````
``````def sum(list: List[Int]): Int =
list match {
// 空のとき
case Nil     => 0 // Nil == List()
// リストの先頭(x) :: 残りの要素
case x :: xs => x + sum(xs)
}

println(sum(List(18, 29, 36, 12, 15)))
// => 110
``````
``````int arr[] = {18, 29, 36, 12, 15};

int sum = 0;
for(int i = 0; i < arr.length(); i++){
sum += arr[i];
}
``````
``````import scala.io._

def getLineLength(lines: List[String]): Int =
lines.length

println(getLineLength(Source.fromFile("memo", "UTF-8").getLines.toList))
=> Number of rows in memo
println(getLineLength(List("aaa", "bbb", "ccc")))
=> 3
``````
``````import scala.io._

def getFileLines(name: String): Int = {
val source = Source.fromFile(name, "UTF-8")
source.getLines.length
}

println(getFileLines("memo"))
=> Number of rows in memo
``````
``````// 整数xを受け取り xより1多い整数とnを掛け合わせる関数を返す関数。
def someFun(x: Int): (Int) => Int = (n: Int) => (x + 1) * n
val f = someFun(5)
// (n: Int) => 6 * n
println(f(3))
// 6 * 3 => 18
``````
``````import scala.concurrent._
import ExecutionContext.Implicits.global

Future(2).map(x => x * 2)
// => Success(4)
// flatMapの例は省略
``````
``````def even(x: Int): Option[Int] =
if(x % 2 == 0) Some(x) // 値があるときは、Some
else None              // 値がないときは、Noneとなります。

even(2).map(x => x * 2)
// => Some(2) => Some(2 * 2) => Some(4)
even(1).map(x => x * 2)
// => None => None

// List同様パターンマッチすることも可能です。
even(10).map(x => x * 2) match{
case Some(x) => println(s"even: \$x")
case None    => println(odd)
}
// => even: 20

Some(Some(1)).flatMap(opt => opt.map(v => v * 2))
// => Some(2)
``````
``````List(List(1,2,3), List(4), List(5, 6)).flatMap{ list => list.map(x => x * 2) }
// => List(2, 4, 6, 8, 10, 12)
``````
``````val list = List(18, 29, 36, 12, 15)
list.map(x => x * 2)
=> List(36, 58, 72, 24, 30)
``````
``````// list.(初期値){値があるときの、処理}
val list = List(18, 29, 36, 12, 15)
val sum    = list.foldLeft(0){(acc, x) => x + acc }
val length = list.foldLeft(0){(acc, x) => 1 + acc }
``````
``````def sum(list: List[Int]): Int =
list match {
// 空のとき
case Nil     => 0 // Nil == List()
// リストの先頭(x) :: 残りの要素
case x :: xs => x + sum(xs)
}

def length(list: List[Int]): Int =
list match {
case Nil     => 0
case x :: xs => 1 + length(xs)
}
``````
``````// 整数xと関数fを受け取り、fにxを適用した値とxを足し、計算結果を返す関数。
def fadd(x: Int, f: (Int) => Int): Int = f(x) + x
println(fadd(3, (x: Int) => x * 2))
// => (3 * 2) + 3 => 9
``````
``````val add = (x: Int, y: Int) => x + y // 式が複数の場合、{}で囲んでもOK！