LoginSignup
0
2

More than 5 years have passed since last update.

PureScript by Example の 5.16, 5.17, 5.18 を読む

Last updated at Posted at 2016-12-18

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

概要

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

今日は 5.16 から 5 章の終わりまでを読んでいく。ソースコードの例は purescript-book の chapter5 にある。

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

前回までのおさらい

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

5 章のここまでに出てきたものは次のとおり。あとは例だけのはずなので、これでほぼすべて。

Language Guide:

PureScript by Example 5.16

type でシノニムを定義している。 type keyword とシノニムは 3 章で出てきた。

type Picture = Array Shape

Language Guide:

昨日の newtype との違いは、type は別名をつけるだけなので互換性があり、 newtype は別の型なので互換性がない。

> type Int' = Int
> :paste
… let
…   x :: Int'
…   x = 123
…
> x
123

> newtype Int'' = Int'' Int
> :paste
… let
…   y :: Int''
…   y = 123
…
Error found:
in module $PSCI
at  line 3, column 7 - line 3, column 7

  Could not match type

    Int

  with type

    Int''


while checking that type Int
  is at least as general as type Int''
while checking that expression 123
  has type Int''
in value declaration y

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

Picture を使って showPicture を定義する。

showPicture :: Picture -> Array String
showPicture = map showShape

手を抜いて purescript-book に書いてあるものを使って psci で試す。

> import Data.Picture
> :paste
… showPicture
…   [ Line (Point { x: 0.0, y: 0.0 })
…          (Point { x: 1.0, y: 1.0 })
…   ]
…
["Line [start: (0.0, 0.0), end: (1.0, 1.0)]"]

良さそう。

PureScript by Example 5.17

今度は dataBounds を定義する。 | が使われていないところを見ると newtype でも良さそうだけど……。

data Bounds = Bounds
  { top    :: Number
  , left   :: Number
  , bottom :: Number
  , right  :: Number
  }

いくつかの Data.Picture の関数を使って bounds を定義する。emptyBounds\/ および shapeBoundsData.Picture の中に定義されているのでそれを見ると良い。

bounds :: Picture -> Bounds
bounds = foldl combine emptyBounds
  where
    combine :: Bounds -> Shape -> Bounds
    combine b shape = shapeBounds shape \/ b

ふむ。

まとめ

5 章を終えた。type data newtype が出た。パターンマッチも出た。{ foo: String | r } のような行多相も出た。

参考

次回以降の 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