【问题标题】:Scala method definition named parameters vs. unnamedScala 方法定义命名参数与未命名参数
【发布时间】:2013-01-30 15:58:34
【问题描述】:

我是 Scala 的新手,我有时会在方法签名方面遇到困难。 让我们来看看这段代码,我对命名参数特别感兴趣,以便对它们进行进一步的操作。

def divide(xs: List[Int]): List[Int] = {
      val mid = xs.length/2
      (xs take mid, xs drop mid)
}

在这里我定义了名为“xs”的输入列表,我在很多网页上都看到过这个约定。但是在大学里我们有另一种方法签名定义方法(我错过了名字,对不起)我们没有命名输入参数但发生模式匹配:

   def mylength: List[Any] => Int = {
     case Nil   => 0
     case x::xs => mylength(xs)+1
   }

在这种情况下,识别输入参数非常简单,因为只有一个。如何在上面显示的编码样式中使用与下面的代码相同的样式以及 2 个或更多输入参数?

   def myConcat(xs: List[Any], ys: List[Any]) = {
              xs ++ ys
   }

对不起我的英语。我在谷歌上没有找到任何东西,因为我不知道要搜索什么字词......

编辑:我必须坚持一个界面。我举了另一个例子,你可以帮助我。 myAppend1 和 myAppend2 的行为方式相同,将新元素放在列表的前面。

   def myAppend1(xs: List[Any], y: Any): List[Any] = {
        y :: xs
   }

我现在的问题是我在 myAppend2 中输入的命名...

  def myAppend2: List[Any] => Any => List[Any] = {
           /* how can i do this here, when no names y/xs are given?*/
   }

【问题讨论】:

  • mylength 不带参数,但返回一个带列表参数的函数,其中myConcat 带两个参数。例如,参见scala-lang.org/api/current/index.html#scala.Function1,关于函数类型。这可能有助于您进行谷歌搜索。我相信会有人来回答你的问题,如果没有,我会在以后有更多时间的时候回答。

标签: scala methods signature


【解决方案1】:

要使用具有 2 个或多个参数的相同样式,只需将参数视为两个的元组:

 def myConcat: (List[Any], List[Any]) => List[Any] = { 
   case (Nil, Nil) => List()
   case (xs,ys) => ... 
 }

我们以myAppend 为例:

 def myAppend2: (List[Any], Any) => List[Any] = {
    case (xs, y) => y :: xs 
 }

这具有(或多或少)相同的签名:

def myAppend1(xs: List[Any], y: Any): List[Any] = {
    y :: xs
}

用法:

scala> myAppend1(List(1,2,3), 4)
res3: List[Any] = List(4, 1, 2, 3)

scala> myAppend2(List(1,2,3), 4)
res4: List[Any] = List(4, 1, 2, 3)

如果您有一个需要 (List[Any], Any) = List[Any] 函数参数的高阶函数,那么两者都可以工作并且(对于大多数实际目的)是等效的。

请注意,通过像这样定义它

def myAppend3: List[Any] => Any => List[Any] = {
   xs => y => y::xs
}

您将创建一个柯里化函数,它在 scala 中具有不同的签名 (从你想要的):

 myAppend3(List(1,2,3), 4) // won't compile
 myAppend3(List(1,2,3))(4) // need to do this

【讨论】:

  • 我不允许更改签名 ;( 当然这会更容易,但“纯功能”不是我 atm 的目标。
  • 但如果没有其他选择 - 很好的解决方案。
  • 感谢您的详细解答。非常感谢!
【解决方案2】:
def myAppend2: List[Any] => Any => List[Any] = { xs => y => 
    y :: xs
}

具有完整形式的函数字面量语法:

def myAppend2: List[Any] => Any => List[Any] = {
    (xs: List[Any]) => {
        (y: Any) => {
            y :: xs
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2020-02-13
    • 2022-11-01
    • 1970-01-01
    • 2020-06-24
    • 2018-05-14
    • 2020-02-16
    • 2021-06-12
    相关资源
    最近更新 更多