[Haskell-cafe] Newbie Question on type constructors

Jon Fairbairn Jon.Fairbairn at cl.cam.ac.uk
Mon Nov 1 15:51:11 EST 2004

On 2004-11-01 at 12:30PST "Brian Beckman" wrote:
> Most interesting discussion -- in reading it, I realized that I had a
> 'hidden agenda' in asking my question (hidden even from myself), and
> that is: can I put interesting functionality, like precondition checks &
> data validation, in data constructors? 

No, though one could make a case that you should be able to.

> I suspect not, and that's why I tend to write something
> like the following:
>   data Shape = Circle Float
>              | Square Float
>     deriving (Eq, Show)
>   circle :: Float -> Shape
>   circle x = if (x <= 0) then error "Bad radius!" else Circle x
> That's fine,


> but I don't know how to prevent users from calling "Circle"
> directly 

Put the data declaration in a module, export the type, but
not the constructor you want to hide:

> module Shape (Shape(Square), circle) where

Jón Fairbairn                                 Jon.Fairbairn at cl.cam.ac.uk

More information about the Haskell-Cafe mailing list