令人困惑的Scala高阶函数调用语法 [英] Confusing Scala Higher order function call syntax

查看:371
本文介绍了令人困惑的Scala高阶函数调用语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对scala中'block'{...}构造的各种用法有点困惑,尤其是在调用如下例所示的高阶函数时。

  def higherOrder(func:Int => Int):Int = {
func(4)
}

val f =((x:Int)=> x * x)

然后我可以像这样调用higherOrder :


  1. higherOrder(f)


  2. higherOrder {f}

  3. higherOrder {x => (1)显而易见,
    但是I($)
    $ / $>
  4. (2)和(3)的语法是如何被编译器解析的
    能不能解释我的头是否可以解释(2)和(3)对应的关于 language specification?

    解决方案

    请参阅 SLS 6.6功能应用程序。函数应用程序定义如下:

      SimpleExpr :: = SimpleExpr1 ArgumentExprs 
    ArgumentExprs :: ='('[Exprs ]')'
    ...
    | [nl] BlockExpr

    BlockExpr

      BlockExpr :: ='{'CaseClauses'}'
    | '{'Block'}'

    因此,在函数或方法名称之后,您可以指定括号中的参数列表或大括号中的表达。


    I am a little confused by the various uses of the 'block' {...} contruct in scala especially when calling a higher order function like in the following example.

    def higherOrder(func: Int => Int): Int = {
      func(4)
    }
    
    val f = ((x: Int) => x*x)
    

    Then I can call higherOrder like so:

    1. higherOrder(f), or

    2. higherOrder {f}, or

    3. higherOrder { x => x*x }

    (1) is obvious, but I can not wrap my head around how the syntax for (2) and (3) are parsed by the compiler Can somebody explain what (2) and (3) correspond to, with regard to the language specification?

    解决方案

    See SLS 6.6 Function Applications. Function application is defined like this:

    SimpleExpr ::= SimpleExpr1 ArgumentExprs
    ArgumentExprs ::= ‘(’ [Exprs] ‘)’
                    ...
                    | [nl] BlockExpr
    

    And BlockExpr is

    BlockExpr ::= ‘{’ CaseClauses ‘}’
                | ‘{’ Block ‘}’
    

    So after function or method name you could specify either arguments list in brackets or expression in braces.

    这篇关于令人困惑的Scala高阶函数调用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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