gpt4 book ai didi

haskell - 在 Haskell 中处理函数中的错误

转载 作者:行者123 更新时间:2023-12-02 04:44:56 25 4
gpt4 key购买 nike

我有一个 sign 函数,它可以返回一个错误。

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*** Exception: Error in sign.

除了异常:++0,我什么都不想。

最佳答案

在这种情况下,您可以而且应该使用 Maybe:

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

signes = mapMaybe signe

您可能需要为 mapMaybe 函数导入 Data.Maybe。

关于haskell - 在 Haskell 中处理函数中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19984864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com