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

北战南征 提交于 2020-01-01 14:21:50

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/18680341/what-is-the-purpose-of-const-id-in-this-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!