[Haskell-beginners] Reading input

Yitzchak Gale gale at sefer.org
Thu Aug 21 04:56:25 EDT 2008


Chaddaï Fouché wrote:
> Another possibility would be a space delimited number list, easier for
> your users to remember :
>
> parseWordList :: (Read a) => String -> [a]
> parseWordList str = map read . words $ str

Even nicer, here is a function that will allow the user
to enter a "list of numbers" in any reasonable format.
If the input doesn't make sense as a "list of numbers",
the empty list is returned:

parseWordList :: (Read a) => String -> [a]
parseWordList = unfoldr $ listToMaybe . concatMap reads . tails

You'll need to import the Data.List and Data.Maybe libraries
for this.

Here is a snippet from a GHCi session that illustrates its use:

Prelude Data.List Data.Maybe> parseWordList "The numbers are 34, 56,
and 22." :: [Int]
[34,56,22]

Regards,
Yitz


More information about the Beginners mailing list