[英]def compose[A,B,C](f: B => C, g: A => B): A => C = {f(g(_))} is noty valid scala declaration?
I am new to scala this might be a cake walk concept but trying to understand why 我是scala的新手,这可能是一个轻而易举的概念,但试图了解原因
def compose[A,B,C](f: B => C, g: A => B): A => C = {f(g(_))}
Is not valid scala declation? 是不是有效的scala decation?
Try 尝试
def compose[A,B,C](f: B => C, g: A => B): A => C = { a: A => f(g(a)) }
The underscore-as-placeholder syntax works inconsistently, and in particular doesn't tend to work in nested function calls like you have here. 下划线-占位符语法不一致,尤其是在像您在此处的嵌套函数调用中不起作用。 A good rule of thumb is that if the underscore syntax is erroring, try expanding it to an explicit lambda and see if it works then. 一条好的经验法则是,如果下划线语法有误,请尝试将其扩展为显式lambda,然后查看其是否有效。
因为f(g(_))
在Scala中表示f(x => g(x))
,而不是x => f(g(x))
。
You need to assign a name to the variable that receives your function g: 您需要为接收函数g的变量分配一个名称:
def compose[A,B,C](f: B => C, g: A => B): A => C = {x => f(g(x))}
You can also do as follows (i renamed the function name to make it clear that is a differente thing) : 您还可以执行以下操作(我已将函数名重命名以使其与众不同):
def myCompose[A,B,C](f: B => C, g: A => B): A => C = f compose g
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.