haskell - catching errors during string parsing -



haskell - catching errors during string parsing -

i want parse string int , utilize this:

string2int :: string -> int string2int str = read str::int

now want grab paring exception/error possible. tried:

import qualified control.exception e eval <- seek (print (string2int "a")) :: io (either e.someexception ()) case eval of left e -> { putstrln "exception"; } right n -> { putstrln "good"; }

but compiler says couldn't match expected type 'e.someexception()' actual type e.ioexception.

what doing wrong?

ok don't know how utilize problem: want somthing this:

loadfunction = { x <- string2int getline if( failed parsing int ) phone call somefunction y <- string2int getline if( failed parsing int ) phone call somefunction otherfunction x y }

i dont know how using answers...

you're using try imported old exceptions mechanism, trying utilize result type if using new extensible control.exception mechanism. utilize e.try instead.

you should ideally import control.exception this:

import prelude hiding (catch) import control.exception

and remove imports of control.oldexception. can utilize functions straight without worrying clashes.

by way, don't have utilize io exceptions handle read errors; can utilize reads instead:

reads :: (read a) => string -> [(a, string)]

here's how i'd write code reads:

case reads "a" of [(a, "")] -> print putstrln "good" _ -> putstrln "exception"

the fact reads returns list a little confusing; practically, can think of returning maybe (a, string) instead. if want version using maybe, can define this:

readmaybe :: (read a) => string -> maybe readmaybe s = case reads s of [(a, "")] -> _ -> nil

which makes code become:

case readmaybe "a" of -> print putstrln "good" nil -> putstrln "exception"

(you can define readmaybe listtomaybe . map fst . filter (null . snd) . reads dave4420 did; they'll equivalent in practice, since none of standard read instances ever homecoming lists of more 1 element.)

in general, should seek , utilize pure error-handling methods whenever possible, , utilize io exceptions when there's no other option, or you're dealing io-specific code (like file/network handling, etc.). however, if want stick exceptions, using e.try instead should prepare error.

based on updated question, however, exceptions might right way go after all; errort work, if you're doing in io start with, there's no harm in using exceptions. write illustration this:

loadfunction = line1 <- getline x <- string2int line1 line2 <- getline y <- string2int line2 otherfunction x y

and utilize e.catch handle exceptions throws; take @ the documentation catch see how that.

haskell

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -