Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a total alternative to the `read` function?

Why does the function read terminate the executable when it cannot parse its argument?

It seems to me that it would be more convenient to have a function of type String -> Maybe a, which returns Nothing if the string couldn't be parsed to the type a, but I can't find anything like it. What am I missing?

like image 691
Guillaume Chérel Avatar asked Mar 05 '17 15:03

Guillaume Chérel


People also ask

How do you read a function?

The notation y=f(x) defines a function named f. This is read as “y is a function of x.” The letter x represents the input value, or independent variable. The letter y, or f(x), represents the output value, or dependent variable.


1 Answers

The function you are looking for is called readMaybe and is defined in the module Text.Read:

https://hackage.haskell.org/package/base-4.9.1.0/docs/Text-Read.html#v:readMaybe

It is available since GHC 7.6. Before that you had to call reads, which returns a (potentially empty) list of parsed values, and pattern match on it.

like image 84
Roman Cheplyaka Avatar answered Oct 20 '22 18:10

Roman Cheplyaka