我有三个函数用来找到一个列表中的第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)
在我看来,第一个函数是最佳实现,因为它最为简洁。但是,其他两个实现方案有什么特点可以使它们更优选吗?进一步地,您如何选择使用guards、if-then-else语句和cases?
case compare a 0 of LT -> ... | EQ -> ... | GT -> ...
,则可以折叠嵌套的case
语句。 - rampioncase compare a 1 of ...
。 - newacct