1

If the constraint has to be set that the Radius of any Circle created must be greater than zero ( Radius > 0 ). How to do it?

data Point = Point Float Float deriving (Show)  
data Radius = Radius Float deriving (Show)  
data Shape = Circle Point Radius deriving (Show)
surface :: Shape -> Float  
surface (Circle _ (Radius r)) = pi * r ^ 2  

If convenient, please give few more examples for how one can set constraint / validations in various scenarios. E.g. data phone can have regex or specific set of starting number (area code or country code etc.).

2 Answers 2

6

The simplest way to achieve validation on the fields of data types is not to export from the module the value constructors, and define and export instead functions that perform the required checks before actually constructing and returning the object using the hidden value constructor.

A simple example with two possible ways to report the error:

module MyModule
( Radius  -- we do not export value constructors
, radius
, radius'
) where

data Radius = Radius Float deriving (Show)

radius :: Float -> Maybe Radius
radius r | r > 0     = Just (Radius r)
         | otherwise = Nothing

radius' :: Float -> Radius
radius' r | r > 0     = Radius r
          | otherwise = error "negative radius"

In this way, the users of your module will only be able to create new values only through the functions you personally defined, and not through the value constructors that would enable them to skip all checks.

0
3

If you want something a little more fun than Riccardo's solution, you could use lenses as your interface to the type. You can do this currently with fclabels, although there isn't a way to distinguish failure on an outer constructor from failure on the inner value you're trying to validate.

I've also written an experimental lens lib that attempts to address that use-case in a more structured way, but I can't really recommend it at this stage.

2
  • What will be basic difference in adapting your suggested fclabels or lens lib and Reccardo's solution in terms of programmer's productivity and maintenance of the code of the application?
    – Optimight
    Jul 20, 2012 at 17:03
  • @Optimight: lenses are very attractive when you need to compose your accessors. So if for some reason you find your circle type is nested in a triangle or something, you can do radius . circle to produce a lens on that nested circle's radius. it's the same idea as what Riccardo is suggesting only better, modulo the extra learning/complexity/additional dependencies
    – jberryman
    Jul 20, 2012 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.