gpt4 book ai didi

haskell - 如何报告 Haskell 代码中的错误

转载 作者:行者123 更新时间:2023-12-02 18:30:23 25 4
gpt4 key购买 nike

我正在编写一个程序,该程序返回列表中的每个第 r 个元素。该列表可以是任何类型。我想在 r 为零时报告错误,但我的代码无法正常工作(当我注释掉错误行时,它工作正常)。谁能告诉我在这种情况下如何报告错误

rthElem :: Int -> [a] -> [a]
rthElem _ [] = []
rthElem 0 (x:xs) = "Error"
rthElem n (x:xs) = rthElem' n 1 (x:xs) where
rthElem' n i (x:xs) = (if (n `divides` i) then
[x] else
[])
++ (rthElem' n (i+1) xs)
rthElem' _ _ [] = []
divides x y = y `mod` x == 0

最佳答案

在这种情况下,您可以使用MaybeEither

这就是也许的样子。 没有什么会成为我们的“错误”。

rthElem :: Int -> [a] -> Maybe [a]
rthElem _ [] = Just []
rthElem 0 (x:xs) = Nothing
rthElem n (x:xs) = Just (rthElem' n 1 (x:xs)) where
rthElem' n i (x:xs) = (if (n `divides` i) then
[x] else
[])
++ (rthElem' n (i+1) xs)
rthElem' _ _ [] = []
divides x y = y `mod` x == 0

main :: IO ()
main = case (rthElem 0 [1..5]) of
Nothing -> putStrLn "Error"
Just elm -> print elm

另一种方法是使用EitherEither 将返回 LeftRight左边将是我们的“错误”。

rthElem :: Int -> [a] -> Either String [a]
rthElem _ [] = Right []
rthElem 0 (x:xs) = Left "Error"
rthElem n (x:xs) = Right (rthElem' n 1 (x:xs)) where
rthElem' n i (x:xs) = (if (n `divides` i) then
[x] else
[])
++ (rthElem' n (i+1) xs)
rthElem' _ _ [] = []
divides x y = y `mod` x == 0

main :: IO ()
main = case (rthElem 0 [1..5]) of
Left err -> putStrLn err
Right elm -> print elm

最好的方法是使用Either。了解有关错误处理的更多信息 here .

关于haskell - 如何报告 Haskell 代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374993/

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