Haskell 勉強メモ5

let式

let 式は変数を束縛する。 let 式自身も式。式であるとは、「値を持つ」ということ。

円柱の表面積を求める。

cylinder :: Double -> Double -> Double
cylinder r h =
  let sideArea = 2 * pi * r * h
      topArea = pi * r ^ 2
   in sideArea + 2 * topArea

*Main> cylinder 4 10
351.85837720205683

let は式であるので、コードの中のどんなところでも使える。

*Main> 4 * (let a = 9 in a + 1) + 2
42

-- ローカルスコープに関数を作る
*Main> [let square x = x * x in (square 5, square 3, square 2)]
[(25,9,4)]

-- タプル要素を分解してそれぞれの名前に束縛する
*Main> (let (a, b, c) = (1, 2, 3) in a + b + c) * 100
600

case 式

パターンマッチで使う。

head' :: [a] -> a
head' xs = case xs of
  [] -> error "No head for empty lists"
  (x : _) -> x

*Main> head' []
*** Exception: No head for empty lists
CallStack (from HasCallStack):
  error, called at baby.hs:3:9 in main:Main
*Main> head' [1, 2]
1
*Main> 

case 式の構文は下記

 case expression of pattern -> result
                pattern -> result
                pattern -> result

式に合致した最初のパターンが使われる。

case 式はどこでも使える。

describeList :: [a] -> String
describeList ls =
  "The list is "
    ++ case ls of
      [] -> "empty"
      [x] -> "a singleton list"
      xs -> "a longer list"

*Main> describeList []
"The list is empty"
*Main> describeList [1, 2]
"The list is a longer list"
*Main> describeList [1]
"The list is a singleton list"