liveBook · Manning

Newtype idiom

As explained in Learn Haskell by Example

newtype is Haskell syntax for defining a distinct type with exactly one constructor containing exactly one field.

Use newtype when a value needs a distinct type around exactly one field. An AssocMap can wrap a list of key-value pairs while separating its representation from the public API. section 5.2.2

Pair the idiom with a module export list: export AssocMap without its constructor, but expose operations such as member, alter, empty, delete, and insert. This prevents callers from constructing invalid duplicate-key maps directly. section 5.2.2

A protected associative map

module Data.AssocMap (AssocMap, member, alter) where newtype AssocMap k v = AssocMap [(k, v)] member :: Eq k => k -> AssocMap k v -> Bool member key (AssocMap xs) = member' key xs empty :: AssocMap k v empty = AssocMap []

How Learn Haskell by Example covers it

How deep it goes
Defines syntax, constructor hiding, and implementation patterns, but defers technical differences between newtype and data to an appendix.
Examples
Uses AssocMap over key-value lists, with member, alter, empty, delete, and insert operations.
What you can do after
Apply newtype and constructor hiding to build a representation-backed type whose invariants callers cannot bypass directly.
How it connects
Connects newtype with modules, export lists, constructors, pattern matching, and representation invariants.

Also explained in

Compare how 4 books explain newtype idiom →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.