加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 函数文字与函数值

发布时间:2020-12-16 18:06:15 所属栏目:安全 来源:网络整理
导读:试图从 Scala编程,第2版中找出本节的重要性. A function literal is compiled into a class that when instantiated at run- time is a function value. Thus the distinction between function literals and values is that function literals exist in the
试图从 Scala编程,第2版中找出本节的重要性.

A function literal is compiled into a class that when instantiated at
run- time is a function value. Thus the distinction between function
literals and values is that function literals exist in the source
code,whereas function val- ues exist as objects at runtime. The
distinction is much like that between classes (source code) and
objects (runtime).

我真的没有得到他们在这里想说的话.源代码中不存在该函数值,并且在运行时不存在函数文字?

// literal
val addOne = (x: Int) => x + 1

// value
def add1(x: Int): Int = x + 1

我可以传递给另一个函数:

def doThing(thing: Int => Int) = thing(5)

doThing(addOne) // 6
doThing(add1)   // 6

似乎函数文字也放在一个继承自FunctionN的类中(其中N是函数的arity).他们试图在这里做出什么区别?

解决方法

I don’t really get what they’re trying to say here.

您的函数文字和值的示例不准确.本书不是将方法与函数进行比较,而是在函数的两个不同“模式”之间进行区分.提示是第一句话:

A function literal is compiled into a class that when instantiated at
run-time is a function value.

在编译时,您键入:

val addOne = (x: Int) => x + 1

这就是本书所称的“函数文字”(或Anonymous Function).通过键入以下内容来获得字符串文字的方式相同:

val s = "Hello,World"

addOne到编译器是一个Function1 [Int,Int],意思是接受一个I??nt并返回一个Int结果.函数文字语法((x:Int)=> x 1)是FunctionN上的语法糖,其中N由函数的arity确定.

在运行时,编译器通过实例化Function1 [Int,Int]类型的对象来获取此“函数文字”并“将生命放入其中”,从而创建一个可以调用,传递等的函数值.

What distinction are they trying to make here?

本书基本上试图在函数的编译时和运行时表示之间进行区分,因此当他们说“函数文字”时,你会理解他们在谈论前者,当他们说“函数值”时,后者.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读