maxime1992
maxime1992

Reputation: 23793

Handling error in function in Haskell

I have a sign function, which can return an error.

signe :: Int -> Char
signe chiffre
    | chiffre >= 1 && chiffre <= 9 = '+'
    | chiffre == 0 = '0'
    | chiffre >= -9 && chiffre <= (-1) = '-'
    | otherwise = error "Erreur in the sign"

I'd like to make a simple one to return the corresponding code of the sign, but with error handling.

signes liste = [ signe x | x<-liste ]

I give you an example : For now, if I call

signes [1,3,0,-10]

it gives me

++0*** Exception: Error in sign.

I'd like to have nothing instead of Exception: ++0.

Upvotes: 2

Views: 129

Answers (3)

jamshidh
jamshidh

Reputation: 12060

The problem already seems to be answered by Ingo, but I wanted to point out that since you had an error message in the original question, perhaps "Either" would be a better choice here

signe :: Int -> Either String Char
signe chiffre
    | chiffre >= 1 && chiffre <= 9 = Right'+'
    | chiffre == 0 = Right '0'
    | chiffre >= -9 && chiffre <= (-1) = Right '-'
    | otherwise = Left "Erreur in the sign"

where you can get the filtered list with

signes liste = [ x | Right x<-map signe liste ]

Both Maybe and Either are used for error checking, Either gives you the ability to pass an "Exception" up the call chain.

Upvotes: 0

Ingo
Ingo

Reputation: 36339

You can, and should, use Maybe in such cases:

signe chiffre 
   | chiffre >= 1 && chiffre <= 9 = Just '+'
   ....
   | otherwise = Nothing    -- parbleu!!

signes = mapMaybe signe

You may need to import Data.Maybe for the mapMaybe function.

Upvotes: 3

bheklilr
bheklilr

Reputation: 54058

A better way would be to actually use the Maybe type which lets you literally return Nothing or Just aValue. You could rewrite your function as

signe :: Int -> Maybe Char
signe chiffre
    | chiffre >= 1 && chiffre <= 9 = Just '+'
    | chiffre == 0 = Just '0'
    | chiffre >= (-9) && chiffre <= (-1) = Just '-'
    | otherwise = Nothing

Upvotes: 2

Related Questions