Reputation: 33
I'm a bit confused with an exercise. The exercice asked for a function that would take the last but one element from a list and it shows this code as the correct answer.
myButLast :: [a] -> a
myButLast = last . init
myButLast' x = reverse x !! 1
myButLast'' [x,_] = x
myButLast'' (_:xs) = myButLast'' xs
myButLast''' (x:(_:[])) = x
myButLast''' (_:xs) = myButLast''' xs
myButLast'''' = head . tail . reverse
But I just did this and it just worked as asked
myButLast' = init[1,2,3,4]
myButLast'' = last myButLast'
What was all that extra code in the first solution?
Upvotes: 0
Views: 169
Reputation: 3428
The example code shows 5 different ways of implementing myButLast
. Note that myButLast
and myButLast'
are entirely different functions.
About your answer - your intuition is correct, but your function only deals with one input - [1,2,3,4]
. Instead, you can pass any list:
myButLast' xs = init xs
myButLast'' = last myButLast'
Combine them and add a type signature:
myButLast :: [a] -> a
myButLast xs = last $ init $ xs
Which in pointfree style is equal to the first solution:
myButLast :: [a] -> a
myButLast = last . init
Upvotes: 5