kealist
kealist

Reputation: 1689

What is the purpose of (const id) in this function?

I'm trying to get deeper into the functional mindset and looking through solutions to exercises (99 problems).

The first problem is to create a function that returns the last element of the list.

I see the solution:

myLast = foldr1 (const id)

I understand that foldr1 applies a function f to a list l

so if I plug it into an example:

myLast [1,2,3,4,5,6,7]

Which would be "translated to"

foldr1 (const id) [1,2,3,4,5,6,7]

Could someone explain to me what this (const id) is stepping through. I tried researching (const id) in SO as well as Hoogle, but couldn't make much sense of it. Would someone kindly step me through what is happening here?

Upvotes: 2

Views: 905

Answers (1)

fjarri
fjarri

Reputation: 9726

const and id are two separate functions that you can look up on Hoogle. Perhaps after that you can answer your question yourself, but I'll answer it anyway.

const is a function of two arguments that always returns its first argument. id is a function of one argument that always returns its argument.

Therefore (const id) is a function of one argument that always returns id, or, in other words, a function of two arguments that always returns its second argument.

Now foldr1 takes a function of two arguments f elem accum as the first argument, and applies it sequentially to the list, starting from the last element (using it as the initial value for the accumulator). In our case f will always return its second argument, so whatever accum was initialized with (last element of the list), it will stay the same over all iterations and will get returned.

Now you could use seq instead of (const id), but seq is not lazy. Or you could just use last without writing your own function :)

Upvotes: 6

Related Questions