2013-11-14 78 views
2

我有一個sign函數,它可能會返回一個錯誤。Haskell函數中的處理錯誤

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

我想作一個簡單的與錯誤處理返回的跡象,但相應的代碼。

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

我給你舉個例子:現在,如果我叫

signes [1,3,0,-10] 

它給了我

++ 0 ***異常:錯誤的跡象。

我想沒有任何東西,而不是例外:++0

+1

我想通過「嗨大家」開始我的消息,但即使編輯它沒有考慮到... – Maxime

回答

3

可以,而且應該,在這種情況下使用Maybe

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

signes = mapMaybe signe 

您可能需要進口Data.Maybe爲mapMaybe功能。

+0

mapMaybes - >「不在範圍內」。 (我已經在我的工作表的頂部添加了「import Data.List」) 所以我剛剛嘗試過signes = map signe 但是我得到了[只是'+',........,Nothing ] – Maxime

+0

它實際上只是'mapMaybe'。 [見文檔](http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Maybe.html#v:mapMaybe)。 –

+1

謝謝你指出,@AlexReinking,它實際上是'mapMaybe',它在Data.Maybe中。總是把它和'catMaybes'混淆,最後有一個s。上面的結果。 – Ingo

2

更好的方法是實際使用Maybe類型,它可以讓您從字面上返回NothingJust aValue。你可以重寫你的函數作爲

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

的問題似乎已經被英戈回答,但我想指出的是,因爲你在原來的問題有一個錯誤信息,也許「或者」會是一個更好的選擇這裏

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" 

在那裏你可以得到

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

兩個也許,要麼被用於錯誤檢查過濾列表,要麼給你傳遞的能力呼叫鏈上的「例外」。