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

前端 未结 3 998
迷失自我
迷失自我 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:10

    This is just a matter of ordering but I think its very readable and has the same structure as guards.

    nthElement :: [a] -> Int -> Maybe a 
    nthElement [] a = Nothing
    nthElement (x:xs) a = if a  < 1 then Nothing else
                          if a == 1 then Just x
                          else nthElement xs (a-1)
    

    The last else doesn't need and if since there is no other possibilities, also functions should have "last resort case" in case you missed anything.

提交回复
热议问题