How to create a function in Haskell that returns the fifth element from a list.
Something like this:
fifth [] = []!!4
Should return this:
*Main> fifth [1,2,3,20,30,40]
30
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Simply use:
Using
fifth []like you suggest is wrong since that will pattern match the list against the empty list — you simply want to bind a variable name to the full list so that you can use the!!function afterwards.You can even define the function as:
Here we use partial application: you normally think of
!!as a function taking two arguments: a list and an integer. We can provide it with one of the arguments and get a new function (fifth) that only takes a list. When we provide(!!4)with a list, it returns the fifth element:The function is of course a partial function since it will fail for small lists:
That’s to be expected. If you want, you can make it safe by letting it return
Maybe ainstead ofa::Here the first pattern will match lists of length 5 or more, and the second pattern matches anything not matched by the first. You use it like this:
You have now forced yourself to always pattern match the result of
fifthagainst eitherJust aorNothing. This means that when you code callsfifth someList, then it must take into account thatsomeListmight be too short. That way you can ensure at compile time that there wont be any runtime errors from this function.