Skip to content

Commit

Permalink
Introduce Either
Browse files Browse the repository at this point in the history
  • Loading branch information
igrep committed Jun 11, 2023
1 parent 494ca17 commit 6b3d2d5
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions assets/17.md
Expand Up @@ -552,16 +552,20 @@ ghci> mapMaybe (\i -> if i > 10 then Just (i + 3) else Nothing) [1, 11, 5, 20, 1

### 発展編: 詳しいエラー情報を持つ、`Either`

```
こちらも今回の課題では使用しませんが、`Maybe`型に関連とよく似た、もう一つ重要な型を紹介します。`Either`という名前の型で、文字通り「どちらか一方」の値を表現するための型です。早速定義をGHCiの`:i`コマンドで見てみましょう:

```haskell
ghci> :i Either
data Either a b = Left a | Right b -- Defined in ‘Data.Either’
type Either :: * -> * -> *
data Either a b = Left a | Right b
-- Defined in ‘Data.Either’
instance Applicative (Either e) -- Defined in ‘Data.Either’
-- ... 省略 ...
```

型引数を2つとる。1つめは`Left`という値コンストラクターの引数に使われ、2つめは`Right`という値コンストラクターの引数に使われている
`Maybe`型と異なり、`Either`型は異なる2つの型引数`a``b`をとることによって、結果が`a`型の値だった場合`Left``b`型の値だった場合`Right`を、素直に表現できます。

慣習上、`Right`が成功した場合に返す値として使われ、`Left`が失敗した場合に返す値として使われる
慣習上、`Right`が成功した場合に返す値として使われ、`Left`が失敗した場合に返す値として使われます。詳細は課題hoge(22)で解説するので乞うご期待

### 応用編: 実行しうるコマンドを表す型を作る

Expand Down

0 comments on commit 6b3d2d5

Please sign in to comment.