简体   繁体   English

电梯[A,B]中下划线的含义(f:A => B):选项[A] =>选项[B] = _映射f

[英]Meaning of underscore in lift[A,B](f: A => B): Option[A] => Option[B] = _ map f

I'm working through the examples in Runar and Paul's Functional Programming in Scala book, and I've come across the following implementation of the lift function in section 4.3.2: 我正在研究Runar和Paul的Scala中函数式编程中的示例,我在4.3.2节中遇到了以下对lift函数的实现:

def lift[A,B](f: A => B): Option[A] => Option[B] = _ map f

I understand the purpose of the function, but I don't understand the implementation because I don't understand what the underscore represents. 我理解函数的目的,但我不理解实现,因为我不明白下划线代表什么。 I've looked at many other threads about the myriad meanings of underscore in Scala, and while I'm sure those threads must mention this type of use case, I must've missed it. 我已经看过许多其他关于Scala中下划线含义的线索,虽然我确信这些线程必须提到这种用例,但我一定错过了它。

The underscore here is a shorthand for a function. 这里的下划线是函数的简写。 The compiler is smart enough to infer, based on the return type of the method signature, that what is meant is: 编译器足够智能,可以根据方法签名的返回类型推断出的含义是:

def lift[A,B](f: A => B): Option[A] => Option[B] = (_: Option[A]).map(f)

which in turn expands to: 然后扩展到:

def lift[A,B](f: A => B): Option[A] => Option[B] = (o: Option[A]) => o.map(f)

You might want to have a look at this answer . 你可能想看看这个答案 The _ map f is syntactic sugar for x => x map f , the underscore being a placeholder for an argument to an anonymous function. _ map fx => x map f 语法糖 ,下划线是匿名函数参数的占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM