简体   繁体   English

case y :: ys 是什么意思?

[英]What does case y :: ys mean?

I'm trying to make sense of the code below, but got stuck on case y :: ys .我试图理解下面的代码,但卡在case y :: ys How is this defined?这是如何定义的? I don't see any declaration for y , and ys ... Where do they come from?我没有看到yys任何声明......它们来自哪里?

I understand that case matches try to do equals on the object, but case y :: ys seems to be an operation.我知道case匹配尝试在对象上做 equals,但case y :: ys似乎是一个操作。 What is happening here?这里发生了什么?

def f(xs: List[Int], g: (Int, Int) => Boolean) = {
  def h(x: Int, xs: List[Int]): List[Int] =
    xs match {
      case List() => List(x)
      case y :: ys => if (!g(x, y)) x :: xs else y :: h(x, ys)
    }
  (xs :\ List[Int]())(h)
}

I don't see any declaration for y, and ys, so where do they come from?我没有看到 y 和 ys 的任何声明,那么它们来自哪里?

What you see is the declaration.你看到的声明。

A case is able to deconstruct a value (here xs ) into its parts according to a pattern, if that "matches" (see it?).如果“匹配”(看到了吗?),案例能够根据模式将值(此处为xs )解构为它的部分。 Here a list is deconstructed into a head (giving it the name y ) and a tail/rest (giving it the name ys ).这里一个列表被解构为一个头部(命名为y )和一个尾部/其余(命名为ys )。 Those two parts can now be accessed separately in the expression after the arrow.现在可以在箭头后面的表达式中分别访问这两个部分。

case y :: ys =>

This is an equivalent of pattern matching for lists wherein your x matches with head of the list while ys matches with the tail .这相当于列表的模式匹配,其中x与列表的head匹配,而ystail匹配。 In pattern maching allows you to de-structure the input to match a given pattern, in this case a list with y as head and ys as tail在图案MACHING允许你去结构中的输入以匹配给定的图案,在这种情况下与列表y头和ys为尾

Like other answers, case y :: ys matches head (y) and tail (ys) of a list.与其他答案一样, case y :: ys匹配列表的head (y) 和tail (ys)。

It's actually a syntactic sugar, :: is a case class , you can check the docs and case y :: ys equals to case ::(y, ys) .它实际上是一个语法糖, ::是一个case class ,您可以查看文档并且case y :: ys等于case ::(y, ys)

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

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