tags:

views:

87

answers:

3

Hello.

Im writing app in haskell and I would like to know that is the best way to check if users input is ok for example is it int when Im asking for int or if its date when asking for well formed date ?

Thanks for help

+3  A: 

For an Integer the simplest way is to use "reads". This has the type:

type ReadS a = String -> [(a, String)]

reads :: (Read a) => ReadS a

The idea is that for any type which is an instance of the Read class you pass it the string and it tries to parse it as that type. For instance Integer is an instance of Read, so you can think of the type as

reads :: String -> [(Integer, String)]

If it succeeds then the result will contain one entry with the number and the rest of the string. So for instance

reads "45xyz" = [(45, "xyz")]

So in your case just pattern match on [(v, "")] to get the value, and then have acatch-all pattern match complaining that it didn't get an integer.

Doing dates is more complex. Define your format, and then break it up into bits you can recognise using "reads".

Paul Johnson
I don't think `reads` is guaranteed to return just one entry. It could return several possible parses. Not that I've ever seen an implementation do this, but the type signature and description in the Prelude clearly imply it is possible. Hence, I always use a function like @Yitz's `maybeRead`.
MtnViewMark
Thats right. But in the case of integers it will only return zero or one parse. So match on the expected parse, and anything else is an error.
Paul Johnson
A: 

I like to do this with Parsec when it's command line options. How do I do this, given that a command line is a list of strings and not a string? First, you need to create some simple primitives for parsing lists of String (instead of lists of Char):

http://github.com/solidsnack/system-uuid/blob/master/Options.hs

Then you can compose those to parse your options, as I've done at the bottom of this file:

http://github.com/solidsnack/system-uuid/blob/master/Main.hs

This is really the most powerful way to do it and it leverages the heavy investment any Haskell programmer makes in parser combinators (just as heavy as any Perl programmer makes in regexen).

Jason Dusek
+2  A: 
Yitz