简体   繁体   English

在Scala中的case语句中的cons运算符

[英]cons operator in case statements in Scala

So I read about right-associative operators like the cons operator in Scala. 因此,我了解了诸如Scala中的cons运算符之类的右关联运算符。 I'm wondering why they work in case statements. 我想知道为什么它们在case语句中起作用。 It seems like you can pattern match using the cons statement here? 似乎您可以在此处使用cons语句进行模式匹配?

def findKth1[A](k:Int, l:List[A]):A = (k, l) match {
    case (0, h::_) => h
    case(k, _::tail) if k > 0 => findKth1(k - 1, tail)
    case _ => throw new NoSuchElementException
}

findKth1(2, List(3,4,5,6))  

res1: Int = 5

What is the placeholder doing here? 占位符在这里做什么? I've only seen placeholders used in functions like this: <SomeList>.map(_.doThing) . 我只看到占位符用在这样的函数中: <SomeList>.map(_.doThing) Is it the same concept? 是同一概念吗?

The only difference with :: and ::: is that ::: is used for 2 Lists right? :::::的唯一区别是:::用于2个列表,对吗?

tl;dr It isn't pattern matching the operator, it's pattern matching a case class called :: tl; dr不是与运算符匹配的模式,而是与名为::的案例类匹配的模式

There are a couple of things happening at the same time. 同时发生了几件事。 First of all, there may be a bit of confusion, because :: is a method on List: 首先,可能会有些混乱,因为::是List上的一种方法:

val x: List[Int] = 1 :: 2 :: 3 :: Nil

But there is also a case class :: that, according to the docs is: 但是根据文档, 还有一个case class :: :::

A non empty list characterized by a head and a tail.

More info here 更多信息在这里

Scala's case classes automatically come with extractor methods( unapply ), which allow pattern matching, as in case User(name, age) => ... . Scala的案例类自动带有提取器方法( unapply ),该方法允许模式匹配,例如case User(name, age) => ...

You are also allowed to use the case class name in an infix position (although you shouldn't do so, except when the case class is used like an operator, such as in this case). 您还可以在中位置使用案例类名称(尽管您不应该这样做,除非像操作符一样使用案例类,例如在这种情况下)。 So case head :: tail => ... is the same as case ::(head, tail) => ... . 所以case head :: tail => ...case ::(head, tail) => ... More info here 更多信息在这里

When pattern matching, you can use _ to mean that there will be a value there, but you don't care about it, so you aren't providing it a name. 在进行模式匹配时,可以使用_表示在那里会有一个值,但是您并不关心它,因此您没有为其提供名称。

So the three cases you provided are roughly: 因此,您提供的三种情况大致如下:

  • A tuple where the first value is 0, and the second value is a list with a head to be called h , and a tail which we will ignore. 一个元组,其中第一个值为0,第二个值是一个列表,其头部称为h ,而尾部将被我们忽略。
  • A tuple with some integer to be called k , and a list with a head that we don't care about, and a tail, which we will call tail . 一个元组,具有一个称为k整数,一个带有我们不关心的头和尾的列表,我们将其称为tail Also, k must be greater than 0 此外, k必须大于0
  • Anything else, then throw a NoSuchElementException 还有什么,然后抛出NoSuchElementException

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

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