简体   繁体   English

def compose [A,B,C](f:B => C,g:A => B):A => C = {f(g(_))}是不是有效的Scala声明?

[英]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.

相关问题 Scala如何将Seq [(((A,B,C,D),Seq [(E,F,G)])]]转换为Seq [(A,B,C,D,Seq [(E,F,G) ])]? - Scala How to transform Seq[((A, B, C, D), Seq[(E, F, G)])] to Seq[(A, B, C, D, Seq[(E, F, G)])]? 将&#39;A =&gt; F [G [B]]&#39;转换为&#39;F [G [A =&gt; B]&#39;标量 - transform 'A => F[G[B]]' into 'F[G[A=>B]' scala Scalaz monad变形金刚。 将f1:A =&gt; G [B],f2:B =&gt; G [C]函数应用于F [G [A]]对象 - Scalaz monad transformers. Applying f1:A => G[B], f2:B => G[C] function to F[G[A]] object Scala:zipWith [A,B,C](f:Function2 [A,B,C],l1:List [A],l2:List [B]):List [C]方法 - Scala : zipWith[A,B,C](f: Function2[A,B,C], l1 :List[A], l2 :List[B]) : List[C] Method Scala中f(a,b)和f(a)(b)之间的差异 - Difference between f(a,b) and f(a)(b) in Scala 带有子类型的scala中的联合类型:A | B &lt;:A | B | C. - union types in scala with subtyping: A|B <: A|B|C 如何将F [A \\ / B]拆分为(F [A],F [B]) - How to split F[A \/ B] into (F[A], F[B]) 如何从Scala中的=&gt; b =&gt; c得到(a,b)=&gt; c? - How do I get (a, b) => c from a => b => c in Scala? 用于编写链式比较的scala中的DSL,例如&lt;b &lt;= c - DSL in scala to write chain comparisons such as a < b <= c Scala-“ val a = b = c”的赋值关联性 - Scala - the assignment associativity of “val a = b = c”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM