Handling Maybe values with digestive functors ?

25 views
Skip to first unread message

Simon Gardner

unread,
Dec 14, 2014, 11:34:08 AM12/14/14
to snap_fr...@googlegroups.com
Hi,

Can I ask, what is the correct way to handle the following situation?


I have a data type

  1. data Customer = Customer {
  2.   cid :: Maybe T.Text,
  3.   name :: Maybe T.Text,
  4.   phone :: Maybe T.Text,
  5.   web_address :: Maybe T.Text,
  6.   updated :: Maybe T.Text
  7. } deriving (Show)

with which I'd like to create /render a form.

  1. customerForm :: Monad m => Form Html m Customer
  2. customerForm = Customer
  3.   <$> "id" .: text Nothing
  4.   <*> "name" .: text Nothing
  5.   <*> "phone" .: text Nothing
  6.   <*> "web_address" .: text Nothing
  7.   <*> "updated" .: text Nothing

compilation fails with:

  1.   Couldn't match type `T.Text' with `Maybe T.Text'
  2.    Expected type: Form Html m (Maybe T.Text)
  3.      Actual type: Form Html m T.Text
  4.    In the return type of a call of `text'
  5.     In the second argument of `(.:)', namely `text Nothing'
  6.     In the second argument of `(<$>)', namely `"id" .: text Nothing'


Daniel Patterson

unread,
Dec 14, 2014, 12:58:19 PM12/14/14
to snap_fr...@googlegroups.com
Hi Simon,

For your exact case, you want to use 'optionalText' instead of 'text':

http://hackage.haskell.org/package/digestive-functors-0.7.1.1/docs/Text-Digestive-Form.html#v:optionalText

But, more generally, look into the 'validate' and 'validateM'
functions. They allow you to transform values, potentially failing
because they are invalid. For example, 'optionalText' is defined with
'validate':

optionalText :: Monad m => Maybe Text -> Form v m (Maybe Text)
optionalText def = validate opt (text def)
where
opt t
| T.null t = return Nothing
| otherwise = return $ Just t
> --
>
> ---
> You received this message because you are subscribed to the Google Groups
> "Snap Framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to snap_framewor...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Simon Gardner

unread,
Dec 15, 2014, 5:45:08 AM12/15/14
to snap_fr...@googlegroups.com
brilliant, thanks Daniel !
Reply all
Reply to author
Forward
0 new messages