| Copyright | (c) 2015 Frerich Raabe |
|---|---|
| License | BSD3 |
| Maintainer | frerich.raabe@gmail.com |
| Stability | experimental |
| Safe Haskell | None |
| Language | Haskell2010 |
SmartConstructor
Description
This module exposes a makeSmartCtor function which automatically creates
smart constructors for custom newtype'd Haskell types. See
http://wiki.haskell.org/Smart_constructors for a more in-depth
discussion of smart constructors in Haskell.
Smart constructors are useful for imposing additional checks on values; given e.g.
import SmartConstructor newtype Positive = Positive Int newtype NonEmptyList a = NonEmptyList [a] newtype Interval = Interval (Integer, Integer)
You can use makeSmartCtor to generate smart constructors as follows:
-- Defines 'makePositive :: Int -> Maybe Positive' makeSmartCtor defaultOptions ''Positive [|(> 0)|] -- Defines 'makeNonEmptyList :: [a] -> Maybe (NonEmptyList a) makeSmartCtor defaultOptions ''NonEmptyList [|not . null|]
Notice how the third argument defines a predicate; the generated functions
apply this predicate to the given value: if it yields true, the smart
constructor call evaluates to a Just value. If the predicate yields false,
the smart constructor evaluates to Nothing.
By default, the name for the smart constructor is derived from the
type name. A custom name can be specified by modifying the ctorName
field of the defaultOptions:
-- Defines 'createIV :: (Integer, Integer) -> Maybe Interval
makeSmartCtor defaultOptions{ ctorName = "createIV" } ''Interval [|uncurry (<=)|]- data SmartCtorOptions = SmartCtorOptions {}
- defaultOptions :: SmartCtorOptions
- makeSmartCtor :: SmartCtorOptions -> Name -> Q Exp -> Q [Dec]
Documentation
data SmartCtorOptions Source
Values of the SmartCtorOptions type can be passed to makeSmartCtor in
order to customize the generated constructor functions. At this point,
only the name of the function can be changed.
Constructors
| SmartCtorOptions | |
Fields
| |
defaultOptions :: SmartCtorOptions Source
The default smart constructor generation options; the smart constructor function will be named after the type, e.g.
makeSmartCtor defaultOptions ''Foo [|const True|]
defines a function makeFoo.
makeSmartCtor :: SmartCtorOptions -> Name -> Q Exp -> Q [Dec] Source
The makeSmartCtor function creates a smart constructor for the given type, using the given predicate.