[Haskell-beginners] Type system for constructor preconditions
Daniel Trstenjak
daniel.trstenjak at gmail.com
Thu Jan 17 10:41:26 CET 2013
Hi Bryan,
On Wed, Jan 16, 2013 at 03:10:18PM -0800, Bryan Vicknair wrote:
> Ideally, the type system could do these checks, but we don't have dependent
> types so I kept looking. The pattern below uses the type system to force a
> client of the Circle data type to pass in valid (positive) radius. This isn't
> quite what is on the smart constructors wiki page. Does pattern have a name?
> Where can I read more about it? What are the negatives?
It's just a smart constructor. Instead of using one for Circle, you are
now using one for ValidRadius.
You still have the same pattern matching issue, because how would you
access the radius inside of ValidRadius?
But instead of using pattern matching to access the fields of Circle
you could offer accessor functions.
module Circle (Circle, Radius, circle, radius) where
type Radius = Int
data Circle = Circle Radius deriving (Eq, Show)
circle :: Radius -> Maybe Circle
circle r | r > 0 = Just $ Circle r
| otherwise = Nothing
radius :: Circle -> Radius
radius (Circle r) = r
Greetings,
Daniel
More information about the Beginners
mailing list