Write Haskell code in applicative style with <$>, <*>, <*, and *> when steps do not depend on earlier results, and use do or >>= only where a later step needs an earlier result. Use when writing or reviewing Haskell parsers, FromJSON instances, or code that builds a record from several effectful values.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Applicative?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ncaq-applicative)
---
name: applicative
description: Write Haskell code in applicative style with <$>, <*>, <*, and *> when steps do not depend on earlier results, and use do or >>= only where a later step needs an earlier result. Use when writing or reviewing Haskell parsers, FromJSON instances, or code that builds a record from several effectful values.
user-invocable: false
---
# アプリカティブスタイル
前の結果に依存しない処理を組み合わせて値を組み立てるだけの箇所は、
`do`で1つずつ束縛して最後に`pure Record{..}`とするのではなく、
`<$>`と`<*>`のアプリカティブスタイルで書いてください。
前の結果に依存しない処理を`do`で書くと、
読み手には依存があるように見えてしまい、
全ての束縛を読んで依存が無いことを確かめる必要が出るためです。
`ApplicativeDo`が有効なら`do`でもアプリカティブに脱糖されますが、
読み手から依存の有無が見えにくいのは同じです。
```haskell
-- 避ける
version :: Parser Version
version = do
major <- decimal
_ <- char '.'
minor <- decimal
pure Version{..}
-- 良い
version :: Parser Version
version = Version <$> decimal <* char '.' <*> decimal
```
パーサコンビネータのパーサ、
aesonの`FromJSON`のインスタンス、
環境変数などの複数の値を集めてレコードを組み立てる処理などが当てはまります。
```haskell
instance FromJSON Config where
parseJSON = withObject "Config" $ \o ->
Config <$> o .: "name" <*> o .: "port"
```
## 書き方
- `<*>`はコンストラクタの引数の位置で値を対応させます。
同じ型のフィールドが並ぶレコードでは、フィールドの定義の順番と合っていることを確かめます。
- 結果を捨てる区切りなどは、`<*`で後ろに付けるか、`*>`で前に付けます。
- 長くなる部分は`where`で名前を付けて切り出し、全体を1行で読める程度に保ちます。
- 後の処理が前の結果を本当に必要とする箇所だけを、`>>=`や`do`で書きます。
例えば先に読んだ長さの分だけ続きを読む場合や、
先に読んだタグによって続きの処理を変える場合です。
- `f <$> (g <$> p)`は、hlintのFunctor lawの提案に従って`f . g <$> p`にします。