A bit of a neophyte haskell question, but I came across this example in Haskell’s tutorial examples. For ‘find the last element of a list’ there are some obvious versions, like
last' [x] = x last' (_:xs) = last' xs
But I can’t make sense of an alternate version presented:
myLast' = foldr1 (const id)
So, in trying to make sense of what the application of the id function is doing, I tried in ghci:
const id 1 2 -> gives 2
This binds like this:
(const id) 1 2 -> gives 2
And not like this:
const (id 1) 2 -> gives 1
But I’m not making sense of this. (const id) should translate to something like
`(\x y->x) (\x->x)`
Shouldn’t this return a function that simply returns the id of its first element? Or, how is the function order making (const id) behave differently than const?
The definition of
constisHence,
(const id)is a function which takes one argument and always returnsidandThe definition of
foldr1isIf we have
then
and
which agrees with the definition of
last'.