Scala 中右箭头的含义 [英] Right Arrow meanings in Scala

查看:48
本文介绍了Scala 中右箭头的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Programming In Scala 的第 9 章中,有一个这样的示例方法:

In Chapter 9 of Programming In Scala, there is an example method like this:

def twice(op: Double => Double, x: Double) = op(op(x))

作者在书中说:

这个例子中op的类型是双 =>双,这意味着它是一个将一个 Double 作为一个函数参数并返回另一个 Double.

The type of op in this example is Double => Double, which means it is a function that takes one Double as an argument and returns another Double.

我不明白什么是Double =>"双"在这里,在前面的章节中,="出现只表示函数字面量,从来没有像这样写过Type =>"类型",因为按照 Scala 函数字面量语法定义,函数字面量的右边部分是函数体,函数体怎么可能是双"呢??

I don't understand what is "Double => Double" here, in previous chapters, where "=>" appears only means function literal, and never wrote like this "Type => Type", because according to Scala function literal syntax definition, the right part of function literal is the function body, how can a function body be "Double" ?

推荐答案

因为它有两种用法.

首先,您可以使用 => 来定义函数字面量.

First, you could use => to define function literal.

scala> val fun = (x: Double) => x * 2
fun: (Double) => Double = <function1>

scala> fun (2.5)
res0: Double = 5.0

这很容易.但这里的问题是,fun 是什么类型?它是一个以 Double 作为参数并返回 double 的函数",对吗?

It's pretty easy. But the question here is, what type fun is? It is a "function that takes a Double as an argument and return a double", right?

那么我如何用它的类型来注释 fun 呢?那就是 (Double) =>(双).好吧,前面的例子可以改写为:

So how could I annotate fun with its type? That is (Double) => (Double). Well, the previous example could be rewritten to:

scala> val fun: Double => Double = (x: Double) => x * 2
fun: (Double) => Double = <function1>

scala> fun (2.5)                                       
res1: Double = 5.0

好的,那么下面的代码是做什么的?

OK, then what does the following code do?

def twice(op: Double => Double, x: Double) = op(op(x))

好吧,它告诉你 op 是一个 (Double => Double),这意味着它需要一个函数,它接受一个 Double 并返回一个 Double.

Well, it tells you that op is a (Double => Double), which means it needs a function which takes a Double and return a Double.

所以你可以将前面的 fun 函数传递给它的第一个参数.

So you could pass the previous fun function to its first argument.

scala> def twice(op: Double => Double, x: Double) = op(op(x))    
twice: (op: (Double) => Double,x: Double)Double

scala> twice (fun, 10)
res2: Double = 40.0

并且相当于将op替换为fun,将x替换为10,即fun(fun(10)) 结果是 40.

And it will be equivalent to replacing op with fun, and replace x with 10, that is fun(fun(10)) and the result will be 40.

这篇关于Scala 中右箭头的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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