J'ai trois fonctions de trouver le n-ième élément d'une liste:
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)
À mon avis, la première fonction est la meilleure mise en œuvre, car il est le plus concis. Mais est-il rien sur les deux autres implémentations qui en ferait-elle préférable? Et par extension, comment voulez-vous choisir entre l'utilisation de gardes, if-then-else, et les cas?