我有三个函数可以找到列表的第n个元素:
nthElement :: [a] -> Int -> Maybe a
nthElement [] a = Nothing
nthElement (x:xs) a | a <= 0 = Nothing
| a == 1 = Just x
| a > 1 = nthElement xs (a-1)
nthElementIf :: [a] -> Int -> Maybe a
nthElementIf [] a = Nothing
nthElementIf (x:xs) a = if a <= 1
then if a <= 0
then Nothing
else Just x -- a == 1
else nthElementIf xs (a-1)
nthElementCases :: [a] -> Int -> Maybe a
nthElementCases [] a = Nothing
nthElementCases (x:xs) a = case a <= 0 of
True -> Nothing
False -> case a == 1 of
True -> Just x
False -> nthElementCases xs (a-1)
我认为,第一个功能是最好的实现,因为它是最简洁的。但是,其他两种实现方式是否会使它们更受欢迎?通过扩展,您将如何在使用防护,if-then-else语句和案例之间进行选择?
@rampion:您的意思是
—
newacct
case compare a 1 of ...
case
如果使用过的话,您可以折叠嵌套的语句case compare a 0 of LT -> ... | EQ -> ... | GT -> ...