LoginSignup
0
2

More than 5 years have passed since last update.

PureScript by Example 5.7 〜を読む

Last updated at Posted at 2016-12-14

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

概要

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

今日は 5.7 から読んでいく。

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

前回のおさらい

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

Number String Char Boolean Array のパターンマッチを見た。またガードを書くことでさらに分岐できるのを見た。

Language Guide:

PureScript by Example 5.7

Record パターン。

showPerson :: { first :: String, last :: String } -> String
showPerson { first: x, last: y } = y <> ", " <> x

JavaScript の分割代入で別名指定したときっぽい構文。

> :type showPerson
{ first :: String
, last :: String
}
-> String

あれ、PureScript by Example に書いてあるものと動きが違うぞ……。

> showPerson { first: "Phil", last: "Freeman", location: "Los Angeles" }
Error found:
in module $PSCI
at  line 1, column 1 - line 1, column 70

  Type of expression contains additional label location.

while checking that expression { first: "Phil"
                               , last: "Freeman"
                               , location: "Los Angeles"
                               }
  has type { first :: String
           , last :: String
           }
while applying a function showPerson
  of type { first :: String
          , last :: String
          }
          -> String
  to argument { first: "Phil"
              , last: "Freeman"
              , location: "Los Angeles"
              }
in value declaration it

See https://github.com/purescript/purescript/wiki/Error-Code-AdditionalProperty for more information,
or to contribute content related to this error.

やはりエラーになる。

showPerson :: forall r. { first :: String, last :: String | r } -> String
showPerson { first: x, last: y } = y <> ", " <> x
> import Main
> showPerson { first: "Phil", last: "Freeman", location: "Los Angeles" }
"Freeman, Phil"

> :t showPerson
forall r.
  { first :: String
  , last :: String
  | r
  }
  -> String

これで例どおりに動く。

PureScript by Example 5.8

ネストしても良い。なるほど。

type Address = { street :: String, city :: String }

type Person = { name :: String, address :: Address }

livesInLA :: Person -> Boolean
livesInLA { address: { city: "Los Angeles" } } = true
livesInLA _ = false

PureScript by Example 5.9

@ を使えばスコープに名前をつけることができる。ふむ、言葉で言われてもよく分からないけど、マッチさせる前のものを得られるってことみたいだ。

sortPair :: Array Int -> Array Int
sortPair arr@[x, y]
  | x <= y = arr
  | otherwise = [y, x]
sortPair arr = arr

これはたまに要るのでありがたい。

まとめ

これまた中途半端だけど、時間の都合でここまで。

参考

次回以降の TODO

0
2
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
2