LoginSignup
0
2

More than 5 years have passed since last update.

PureScript by Example の 5.15 を読む

Last updated at Posted at 2016-12-17

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

概要

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

今日は 5.15 から読んでいく。ソースコードの例は purescript-book の chapter5 にある。

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

前回までのおさらい

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

Number String Char Boolean Array Record のパターンマッチを見た。またガード・パターンマッチのネスト・ @ で名前付け・ case 式・部分関数と unsafePartial を見た。data で定義できる代数的データ型とそれを使ったパターンマッチを見た。

Language Guide:

PureScript by Example 5.15

newtype 。代数的データ型のうち、ひとつの構築子とひとつの引数だけを取るもののときに使える。つまり既存の型に新しい名前をつけるもの。実行時には同じものとして扱われるが、型システム上は別のものとして扱われる。

Language Guide:

newtype Pixels = Pixels Number
newtype Inches = Inches Number

なるほど。間違えて InchesPixels を指定しなくて済む。実行時には同じものなので、性能上のデメリットがない、と。

ためしてみる。

f :: Inches -> Number
f (Inches n) = n
> f (Inches 10.0)
10.0

> f (Pixels 10.0)
Error found:
in module $PSCI
at  line 1, column 4 - line 1, column 15

  Could not match type

    Pixels

  with type

    Inches


while checking that type Pixels
  is at least as general as type Inches
while checking that expression Pixels 10.0
  has type Inches
in value declaration it

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

当然、エラーになる。

pulp browserify した結果を見てみる。確かに違いがない。

// ...
// Generated by psc version 0.10.2
"use strict";
var Pixels = function (x) {
    return x;
};
var Inches = function (x) {
    return x;
};
var f = function (v) {
    return v;
};
module.exports = {
    Inches: Inches,
    Pixels: Pixels,
    f: f
};
// ...

まとめ

newtype だけ。進んでいない。

参考

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