Guards vs. if-then-else vs. cases in Haskell

前端 未结 3 959
迷失自我
迷失自我 2021-01-29 18:09

I have three functions that find the nth element of a list:

nthElement :: [a] -> Int -> Maybe a 
nthElement [] a = Nothing
nthElement (x:xs) a | a <= 0          


        
3条回答
  •  迷失自我
    2021-01-29 19:12

    I know this is question about style for explicitly recursive functions, but I would suggest that the best style is finding a way to reuse existing recursive functions instead.

    nthElement xs n = guard (n > 0) >> listToMaybe (drop (n-1) xs)
    

提交回复
热议问题