(const id)在此函数中的作用是什么? [英] What is the purpose of (const id) in this function?

查看:151
本文介绍了(const id)在此函数中的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更深入地研究功能思维,并寻找练习的解决方案(99个问题).

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.

我看到了解决方法:

myLast = foldr1 (const id)

我知道foldr1将函数f应用于列表l

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]

将被翻译为"

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

有人可以向我解释一下此(常量ID)正在执行的操作.我曾尝试在SO和Hoogle中研究(const id),但没有太多意义.有人会帮我逐步了解这里发生的事情吗?

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?

推荐答案

constid是可以在Hoogle上查找的两个独立函数.也许之后您可以自己回答问题,但是我还是会回答.

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是两个参数的函数,该参数始终返回其第一个参数. id是一个参数的函数,该参数始终返回其参数.

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.

因此,(const id)是一个始终返回id的自变量的函数,换句话说,就是两个始终返回其第二自变量的自变量的函数.

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将两个自变量f elem accum作为第一个自变量,然后从最后一个元素开始将其依次应用于列表(将其用作累加器的初始值).在我们的例子中,f将始终返回其第二个参数,因此,无论accum用(列表的最后一个元素)初始化,它在所有迭代中都将保持不变并得到返回.

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.

现在您可以使用seq代替(const id),但是seq并不懒惰.或者,您可以只使用last而不编写自己的函数:)

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

这篇关于(const id)在此函数中的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆