List Haskell错误处理
我有一个从元组列表中查找值的函数,我正在尝试调整此函数,以便如果值不在元组列表中,则该函数会识别它,当前代码块下方会抛出错误List Haskell错误处理,list,haskell,List,Haskell,我有一个从元组列表中查找值的函数,我正在尝试调整此函数,以便如果值不在元组列表中,则该函数会识别它,当前代码块下方会抛出错误 findint :: String -> [(String,Int)] -> [Int] findint "" xs = [0] findint a xs = [y | (x,y) <- xs, x == a] findint::String->[(String,Int)]->[Int] findint“”xs=[0] findint a xs=[y
findint :: String -> [(String,Int)] -> [Int]
findint "" xs = [0]
findint a xs = [y | (x,y) <- xs, x == a]
findint::String->[(String,Int)]->[Int]
findint“”xs=[0]
findint a xs=[y |(x,y)您可以使用模式匹配来实现这一点,例如使用模式保护:
findint :: String -> [(String,Int)] -> [Int]
findint "" xs = [0]
findint a xs | res@(_:_) <- [y | (x,y) <- xs, x == a] = res
| otherwise = error "Empty result"
也就是说,Haskell程序员通常不喜欢使用错误,因为不能从签名中派生错误。通常,可能
用于非全部函数:
findint :: String -> [(String,Int)] -> Maybe [Int]
findint "" xs = Just [0]
findint a xs | null res = Nothing
| otherwise = Just res
where res = [y | (x,y) <- xs, x == a]
findint::String->[(String,Int)]->可能[Int]
findint“”xs=Just[0]
findint a xs | null res=Nothing
|否则=只是res
其中res=[y |(x,y)这是您想要的行为吗
Prelude> findInt s = map snd . filter ((== s) . fst)
Prelude> findInt "ohai" [("hello", 0), ("ohai", 2), ("ohai", 3)]
[2,3]
没有匹配项会返回空列表。我认为这是合理的。但是这里有一个类型错误:您返回一个[Int]
s列表,但是您的第一个子句返回一个Int
(不是Int
s列表)@WillemVanOnsem我已经编辑了问题中的代码,现在是否正确?是的,现在它将编译。您是否必须返回[0]
,例如不是空列表[]
当然取决于您。@WillemVanOnsem谢谢,但是,您知道我如何解决我的初始问题吗?这很有用,但是我可能对我的问题措词不好。我实际上并不想抛出异常。我正在尝试让函数返回一些东西,我可以在稍后的if语句中使用这些东西来确定更多内容代码应该基于“findint”函数来执行,该函数是否在元组列表中查找项。这正是您可以使用Maybe
(最后一部分)执行的操作。因此,我们返回一个Nothing
。
Prelude> findInt s = map snd . filter ((== s) . fst)
Prelude> findInt "ohai" [("hello", 0), ("ohai", 2), ("ohai", 3)]
[2,3]