I want to get a list but the last and the first elements. What is the most efficient way?
middle = init . tail
or:
middle = tail . init
And in the case of drop the n-first elements and the n-last elements?
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.
It doesn’t matter (much) either way. Note that
tailis O(1) whereasinitis O(n). If you take thetailfirst theninithas to examine (n-1) constructors, for a total of n constructors examined.If you take the
initfirst theninitexamines n constructors andtailexamines 1, for a total of n+1 constructors examined.So it’s every so slightly more efficient to do
init . tail, but not so much more efficient that you should worry about it.The same applies to dropping the first k elements from the front and end of the list, except that it might make more of a difference. If you drop the initial elements first, then they don’t have to be examined when dropping the final elements, and you save a bit of time, so you should do
which examines n constructors, rather than
which examines n+k constructors.