mcjkwlczk
mcjkwlczk

Reputation: 145

Implementing last with foldr1

I've a problem with implementing the last function using foldr1. I assume that it takes the right most element and treats it like the accumulator value, then applies binary function to the accumulator and its neighbor until it reaches the beginning of a given list. However, the code shown below doesn't work. Could someone tell me what's wrong with it? Instead of returning the last element it prints out the first one

last' list = foldr1 (\acc _ -> acc) list

Upvotes: 0

Views: 349

Answers (1)

genisage
genisage

Reputation: 1169

foldr :: (a -> b -> b) -> b -> [a] -> b

As you can see, foldr makes the accumulator the second argument, while the value from the list is the first. foldr1 behaves the same way. So, as Lee said, you need to have your lamdba return the second argument rather than the first. Alternatively, you could say foldr1 (flip const)

Upvotes: 1

Related Questions