[Haskell-cafe] Automatically generate sum type members -> [String]

Joachim Breitner mail at joachim-breitner.de
Tue May 19 09:15:25 UTC 2015


Hi,

Am Dienstag, den 19.05.2015, 12:03 +0300 schrieb Anatoly Zaretsky:
> On Tue, May 19, 2015 at 2:20 AM, Cody Goodman
> <codygman.consulting at gmail.com> wrote:
> >
> > data Codes = A0100A | A0500A deriving Show
> >
> > codeExists "A0100A" = True
> > codeExists "A0500A" = True
> > codeExists _ = False
> >
> 
> data Codes = A0100A | A0500A deriving Read
> 
> codeExists code =
>   case reads code of
>     [(_, "")] -> True
>     _ -> False
> 
> Or with -XPatternGuards:
> 
> codeExists code | [(_, "")] <- reads code = True
>                 | otherwise = False

since base-4.6, there is 
        readMaybe :: Read a => String -> Maybe a
in Text.Read. So it might be nicer to write
        codeExists code = isJust (readMaybe code :: Maybe Codes)

Greetings,
Joachim

-- 
Joachim “nomeata” Breitner
  mail at joachim-breitner.dehttp://www.joachim-breitner.de/
  Jabber: nomeata at joachim-breitner.de  • GPG-Key: 0xF0FBF51F
  Debian Developer: nomeata at debian.org
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: This is a digitally signed message part
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20150519/e5d117c4/attachment.sig>


More information about the Haskell-Cafe mailing list