More Related Content Similar to 命令プログラミングから関数プログラミングへ Similar to 命令プログラミングから関数プログラミングへ (20) More from Naoki Kitora (7) 命令プログラミングから関数プログラミングへ3. 関数プログラミングの関数
数学でいうところの関数
f(x) = x + 1
だから Scala では
•関数定義に = (イコール) を使用
•関数内で最後に評価された値が返る
def f(x: Int) {x + 1}
Which
is def f(x: Int) = return x + 1
better?
def f(x: Int) = x + 1
※注: 上の 2つは正しいコードではありません。
6. i = i + 1;
最初に見たとき違和感ありませんでしたか?
13. f(0) = 0
f(n) = f(n - 1) + n
def f(n: Int): Int =
if (n = 0) 0
else f(n - 1) + n
15. 階乗
f(0) = 1
f(1) = 1
f(2) = 2 * 1
f(3) = 3 * 2 * 1
...
f(n) = n * ... * 3 * 2 * 1
16. 階乗 (一般化)
f(0) = 1
f(1) = 1 * f(0)
f(2) = 2 * f(1)
f(3) = 3 * f(2)
...
f(n) = n * f(n - 1)
17. f(0) = 1
f(n) = n * f(n - 1)
def f(n: Int): Int =
if (n = 0) 1
else n * f(n - 1)
20. リストの定義
• 空リスト Nil はリスト
• head が要素、tail がリストなら
head :: tail もリスト
自身を使って定義されたデータ型
•再帰的なデータ型
•自己参照をするデータ型
21. 例示
1 :: 5 :: 1 :: 2 :: 8 :: Nil
:: は右結合なので
1 :: (5 :: (1 :: (2 :: (8 :: Nil))))
1 :: (5 :: 1 :: 2 :: 8 :: Nil)
5 :: (1 :: 2 :: 8 :: Nil)
1 :: (2 :: 8 :: Nil)
2 :: (8 :: Nil)
8 :: Nil
22. 一般化
sum(1 :: 5 :: 1 :: 2 :: 8 :: Nil)
1 + sum(5 :: 1 :: 2 :: 8 :: Nil)
5 + sum(1 :: 2 :: 8 :: Nil)
1 + sum(2 :: 8 :: Nil)
2 + sum(8 :: Nil)
8 + sum(Nil)
sum(Nil) = 0
head + sum(tail)
23. sum(Nil) = 0
head + sum(tail)
def sum(list: List[Int]): Int =
if (list.isEmpty) 0
else list.head + sum(list.tail)
def sum(list: List[Int]): Int = list match {
case Nil => 0
case head :: tail => head + sum(tail)
}
26. お薦め書籍
Scala ではなく OCaml だが
関数プログラミングの基礎
が身につけられる
プログラミングの基礎
浅井健一
サイエンス社
27. 木虎 直樹
@kitora_naoki
テキストマイニング
プログラミング
Scala, Java, JavaScript, Python, OCaml
インフラ
network, Web, AP, RDBMS, MTA, DNS, etc.