パターンマッチの

ススメ

@nakamura_to

自己紹介

  • 名前: 中村
  • 作ったもの
    • Doma: JavaのO/Rマッパー
    • Soma: F#で作った.NET用のO/Rマッパー
    • KageDB: HTML5のIndexedDBのラッパー
  • 作っているもの
    • Tranq: F#によるF#のためのO/Rマッパー

match ... withのススメ


type Shape =
  | Square of int
  | Rectangle of int * int
					

let printArea shape =
  match shape with
  | Square x -> printfn "正方形の面積:%5d" (x * x)
  | Rectangle(w, h) -> printfn "長方形の面積:%5d" (w * h)

printArea (Square 10)         // 正方形の面積:  100
printArea (Rectangle(5, 8))   // 長方形の面積:   40
					

functionのススメ


type Shape =
  | Square of int
  | Rectangle of int * int
					

let printArea = function
  | Square x -> printfn "正方形の面積:%5d" (x * x)
  | Rectangle(w, h) -> printfn "長方形の面積:%5d" (w * h)

printArea (Square 10)         // 正方形の面積:  100
printArea (Rectangle(5, 8))   // 長方形の面積:   40
					

単一ケースの判別共用体で

パラメーターパターンのススメ


type Circle = Circle of float

let printArea (Circle r) =
  printfn "面積: %f" (r * r * System.Math.PI)

printArea (Circle 10.0) // 面積: 314.159265

単一ケースの判別共用体で

パラメーターパターン: 応用


type StatefulFunc<'state, 'result> = 
  StatefulFunc of ('state -> 'result * 'state)

let Run (StatefulFunc f) initialState =
  f initialState

レコードで

パラメータパターンのススメ


type Employee = {Name: string; Age: int; PhoneNo: string}

let printNameAndAge {Name = name; Age = age} =
  printfn "名前: %s, 年齢: %d" name age

let emp = {Name = "Jhon"; Age = 30; PhoneNo = "030123456789"}
printNameAndAge emp // 名前: Jhon, 年齢: 30

入れ子のレコードで

パラメータパターンのススメ


type City = {Name: string}
type Address = {City: City; PhoneNo: string}
type Employee = {Name: string; Age: int; Address: Address}

let printNameAndCity {Name = name; Address = {City = {Name = cname}}} =
  printfn "名前: %s, 都市: %s" name cname

let emp = 
  { Name = "Jhon"
    Age = 30
    Address = 
    { City = {Name = "東京"}
      PhoneNo = "03123456789"}}
printNameAndCity emp // 名前: Jhon, 都市: 東京

まとめ

  • match ... withが基本
  • functionを使うと簡潔に
  • 単一ケースの判別共用体のパラメーターパターン お奨め!
  • レコードでもパラメーターパターン
  • 参考

おわり


ありがとうございました

fsharp pattern matching

By nakamura_to

fsharp pattern matching

  • 2,286