nix-playgraound/notes/009-haskell-dependencies.md
2026-04-23 11:15:05 +02:00

71 lines
1.8 KiB
Markdown

# Haskell Dependencies
This note covers `07-haskell-deps/`, which builds a small Haskell program that depends on external libraries from the Haskell package set.
---
## 1. What This Example Adds
The earlier Haskell examples stayed close to `base` and local modules.
This example adds three common Haskell libraries:
- `aeson` for JSON decoding,
- `text` for string data in the parsed value, and
- `bytestring` for the raw input passed into the decoder.
That makes the example useful for two reasons:
- it shows how Cabal `build-depends` entries become Nix build inputs automatically, and
- it demonstrates a more realistic program shape than a pure string concatenation example.
---
## 2. The Important Point About Dependencies
The flake still uses the same Nix expression pattern as `05-haskell/`:
```nix
project = haskellPackages.callCabal2nix "mini-json" ./. { };
```
The external libraries are not listed again in `flake.nix`. They are declared in `mini-json.cabal`, and `callCabal2nix` translates that Cabal package
description into a Nix derivation.
That is the main teaching point: Cabal remains the source of truth for Haskell package dependencies, while the flake decides how the package is
exposed as a build, app, dev shell, and check.
---
## 3. The Library Function
The library exposes one function:
```haskell
greetFromJson :: ByteString -> Either String String
```
It decodes a JSON object with a `name` field and returns a greeting string. The executable wraps that function in a small CLI, and the test suite
checks both a valid input and an invalid one.
That keeps the example focused on dependency usage, not CLI design.
---
## 4. Commands to Try
```bash
cd 07-haskell-deps
nix develop
cabal run
cabal run -- '{"name":"flakes"}'
cabal test
nix build
./result/bin/mini-json '{"name":"flakes"}'
nix run . -- '{"name":"flakes"}'
nix flake check
```