LoginSignup
1
2

More than 5 years have passed since last update.

PureScript by Example の 6.5, 6.6 を読む

Last updated at Posted at 2016-12-21

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

概要

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

今日は 6.5, 6.6 を読む。ソースコードの例は purescript-book の exercises/chapter6 にある。

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

この章のおさらい

この章では型クラス (type classes) を扱うらしい。

class / instance キーワードおよび型クラス Show / Eq / Ord / Field / Semigroup / Monoid / Foldable / Functor を見た。必要に応じて :: 演算子で型を指定する方法も見た。

Pursuit:

PureScript by Example 6.5

型注釈 (Type Annotations) 。関数の型に制約をつけることができる。 =>

threeAreEqual :: forall a. Eq a => a -> a -> a -> Boolean
threeAreEqual a1 a2 a3 = a1 == a2 && a2 == a3

showCompare :: forall a. (Ord a, Show a) => a -> a -> String
showCompare a1 a2 | a1 < a2 =
  show a1 <> " is less than " <> show a2
showCompare a1 a2 | a1 > a2 =
  show a1 <> " is greater than " <> show a2
showCompare a1 a2 =
  show a1 <> " is equal to " <> show a2

aEq インスタンスが存在する場合だけ引数に取ることができる……みたいな感じ。

> import Prelude ((+))
> :t \x -> x + x
forall t2. (Semiring t2) => t2 -> t2

ある程度、推論もするらしい。

PureScript by Example 6.6

インスタンスの重複はエラーになる。

PureScript by Example とは違う例を試そうとしたら orphan instance というエラーを出してしまった。参考: Orphan instances - maoeのブログdata 定義とは別のところで instance を定義することを許していないのか。

> import Prelude
> :paste
… instance showBoolean :: Show Boolean where
…   show true = "true"
…   show false = "false"
…
Error found:
in module $PSCI

  Type class instance showBoolean for

    Data.Show.Show Boolean

  is an orphan instance.
  An orphan instance is an instance which is defined in neither the class module nor the data type module.
  Consider moving the instance, if possible, or using a newtype wrapper.

in type class instance

  Data.Show.Show Boolean


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

どちらにせよ newtype で別の型にしてから、それへの instance にしろ、ということらしい。

まとめ

=> はざっと眺めるだけでも出てくるし、雰囲気で読めるので良し。インスタンスの重複は許さないことでシンプルになるんだろうな、きっと。

明日で年内の業務が終わる (日記) 。

次回以降の TODO

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