49 lines
1.2 KiB
Markdown
49 lines
1.2 KiB
Markdown
|
|
# Haskell Type Classes and Custom Instances
|
||
|
|
|
||
|
|
This note covers `11-haskell-typeclasses/`, which defines a custom type class and several instances that share one rendering interface.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 1. Why Type Classes Matter
|
||
|
|
|
||
|
|
Type classes let you describe a capability independently from any one data type.
|
||
|
|
|
||
|
|
This example introduces:
|
||
|
|
|
||
|
|
- `Renderable` as a capability,
|
||
|
|
- `Environment`, `BuildState`, and `Deployment` as domain types, and
|
||
|
|
- `DeploymentReport` as a wrapper type for a whole collection.
|
||
|
|
|
||
|
|
Each type gets its own `Renderable` instance, but all of them can be used through the same `render` function.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 2. Why the Instances Are Separate
|
||
|
|
|
||
|
|
Each instance decides how that type should appear:
|
||
|
|
|
||
|
|
- `Environment` renders short environment names,
|
||
|
|
- `BuildState` renders status text, and
|
||
|
|
- `Deployment` combines those smaller renderings into one message.
|
||
|
|
|
||
|
|
That shows the core value of type classes: behavior is attached per type, while the calling code can stay generic.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## 3. Commands to Try
|
||
|
|
|
||
|
|
```bash
|
||
|
|
cd 11-haskell-typeclasses
|
||
|
|
|
||
|
|
nix develop
|
||
|
|
cabal run
|
||
|
|
cabal run -- production failed 2
|
||
|
|
cabal test
|
||
|
|
|
||
|
|
nix build
|
||
|
|
./result/bin/mini-render production failed 2
|
||
|
|
|
||
|
|
nix run . -- production failed 2
|
||
|
|
nix flake check
|
||
|
|
```
|