LoginSignup
0
1

More than 5 years have passed since last update.

PureScript by Example の 5 章の前半を読む

Last updated at Posted at 2016-12-13

この記事は (bouzuya) PureScript Advent Calendar 2016 の 13 日目。 (bouzuya) PureScript Advent Calendar 2016 は bouzuya の PureScript 学習の記録だ。

概要

PureScript by ExamplePureScript Language GuidePursuit を見ながら進めていく。

今日は PureScript by Example の 5 章の前半を読む。

※注意事項: 英語と日本語訳では大きな差異がある。0.10.x に対応している英語の側で進める。

前回のおさらい

この章では代数的データ型 (algebraic data type) とパターンマッチ (pattern matching) および行多相 (row polymorphism) を扱うらしい。

Language Guide:

PureScript by Example 5.3

簡単なパターンマッチの例。

gcd :: Int -> Int -> Int
gcd n 0 = n
gcd 0 m = m
gcd n m = if n > m
            then gcd (n - m) m
            else gcd n (m - n)

イメージどおりに動く (雑) 。引数で n 0 0 m n m というパターンを用意し、それにマッチした場合の結果を書いておく。

PureScript by Example 5.4

シンプルなパターン。イメージどおりに動く (雑) 。 Number String Char Boolean のリテラルとワイルドカードパターン (_) が動作すると書いてある。なるほど。

fromString :: String -> Boolean
fromString "true" = true
fromString _      = false

toString :: Boolean -> String
toString true  = "true"
toString false = "false"

代数的データ型が章の名に含まれているので、それらのパターンマッチも出てくるはずだ。

これらの例でぼくが面白いと感じる点は fromString _toString false の行を削除するとコンパイルエラーになることだ。代数的データ型の話がまだ出てきていないので書きづらいのだけど、 Booleantruefalse からなる。その両方を網羅していない場合はコンパイルエラーになる。

PureScript by Example 5.5

| でガードを書けるらしい。さらに分けられる。ふむ。

gcd :: Int -> Int -> Int
gcd n 0 = n
gcd 0 n = n
gcd n m | n > m     = gcd (n - m) m
        | otherwise = gcd n (m - n)

PureScript by Example 5.6

今日は Array パターンで終わろう。Array リテラルでマッチできる。

isEmpty :: forall a. Array a -> Boolean
isEmpty [] = true
isEmpty _ = false

takeFive :: Array Int -> Int
takeFive [0, 1, a, b, _] = a * b
takeFive _ = 0
> import Prelude
> :paste
… let
…   takeFive [0, 1, a, b, _] = a * b
…   takeFive _ = 0
…
> takeFive [0, 1, 2, 3, 4]
6

> takeFive [1, 2, 3, 4, 5]
0

> takeFive []
0

> takeFive [0, 1, 2, 3, 4, 5]
0

なるほど。これは良い。

Array パターンは固定長を前提としているらしい。可変長にしたいなら Data.List を使えと。なるほど。

参考

次回以降の TODO

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1