Haskell Programming Language Haskell n http www haskell

  • Slides: 44
Download presentation
第2章 言語プログラミングの言語 Haskell Programming Language

第2章 言語プログラミングの言語 Haskell Programming Language

関数型言語Haskell n ホームページ http: //www. haskell. org/ n システムHugs http: //haskell. cs. yale. edu/hugs/

関数型言語Haskell n ホームページ http: //www. haskell. org/ n システムHugs http: //haskell. cs. yale. edu/hugs/ n 参考書 n n ホームページを参照 Bird, R. and Wadler, P. : Introduction to Functional Programming, Prentice-Hall, 1988. (邦訳: 武市正人訳, 関数プログラミング, 近代科学 社, 1991, ISBN 4 -7649 -0181 -1)

式・値 n 式の評価:式=>値 Prelude> 24 Prelude> 26 Prelude> 1. 6 Prelude> 0. 6 Prelude>

式・値 n 式の評価:式=>値 Prelude> 24 Prelude> 26 Prelude> 1. 6 Prelude> 0. 6 Prelude> 1 3*8 2+3*8 2^3/5 mod 3 2 3 `mod` 2 3 `div` 2

関数の定義と適用 n 定義 square : : Int -> Int square x = x *

関数の定義と適用 n 定義 square : : Int -> Int square x = x * x n 適用 square 5 + 2

演算子と関数 n 2引数関数の演算子化 n 関数名を逆引用符(アクサングラーブ)で囲む sumsquares x y = square x + square y

演算子と関数 n 2引数関数の演算子化 n 関数名を逆引用符(アクサングラーブ)で囲む sumsquares x y = square x + square y where square z = z * z sumsquares 3 4 3 `sumsquare` 4

標準的な演算子例 infixl 9 !! infixr 9. infixr 8 ^ infixl 7 * infix 7

標準的な演算子例 infixl 9 !! infixr 9. infixr 8 ^ infixl 7 * infix 7 /, `div`, `rem`, `mod` infixl 6 +, infix 5 \ infixr 5 ++ infix = 4 ==, /=, < =, > infix 4 `elem`, `not. Elem` infixr 3 && infixr 2 ||

再帰的な定義 n 定義する関数の定義式のなかにそれ自体 が現れる factorial 0 = 1 factorial (n+1) = n * factorial

再帰的な定義 n 定義する関数の定義式のなかにそれ自体 が現れる factorial 0 = 1 factorial (n+1) = n * factorial n = if x==0 then 1 else n*factorial(n-1)

値の列挙によるデータ型の定義 data Day = Sun | Mon | Tue | Wed | Thu |

値の列挙によるデータ型の定義 data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat workday : : Day -> Bool workday Sun = False workday Mon = True workday Tue = True workday Wed = True workday Thu = True workday Fri = True workday Sat = False

構成法の列挙による型の定義 data Figure = Circle Float |Rectangle Float n n n 構成子Circle, Rectangle 半径が

構成法の列挙による型の定義 data Figure = Circle Float |Rectangle Float n n n 構成子Circle, Rectangle 半径が 5. 2 の円: Circle 5. 2 辺が 3. 2 と 2. 5 の長方形は?

リストのパターン照合 head : : [a] -> a head (x: xs) = x tail :

リストのパターン照合 head : : [a] -> a head (x: xs) = x tail : : [a] -> [a] tail (x: xs) = xs sum : : [Int] -> Int sum [] = 0 sum (x: xs) = x + sum xs

関数型による 抽象型 Assoc a b の実現 type Assoc a b = a -> b

関数型による 抽象型 Assoc a b の実現 type Assoc a b = a -> b none : : Assoc a b none x = undefined lookup : : Assoc a b -> a -> b lookup h x = h x update : : Eq a => Assoc a b -> a -> b -> Assoc ab update h x v y | x==y =v | otherwise = lookup h y