Scala中的切片符号?

2024-05-23 18:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

Scala中有类似于the slice notation in Python的东西吗?

我认为这真的是一个有用的操作,应该包含在所有语言中。


Tags: thein语言slicescalanotation
3条回答
scala> import collection.IterableLike
import collection.IterableLike

scala> implicit def pythonicSlice[A, Repr](coll: IterableLike[A, Repr]) = new {
     |   def apply(subrange: (Int, Int)): Repr = coll.slice(subrange._1, subrange._2)
     | }
pythonicSlice: [A,Repr](coll: scala.collection.IterableLike[A,Repr])java.lang.Object{def apply(subrange: (Int, Int)): Repr}

scala> val list = List(3, 4, 11, 78, 3, 9)
list: List[Int] = List(3, 4, 11, 78, 3, 9)

scala> list(2 -> 5)
res4: List[Int] = List(11, 78, 3)

这样行吗?

免责声明:未正确概括。


编辑:

scala> case class PRange(start: Int, end: Int, step: Int = 1)
defined class PRange

scala> implicit def intWithTildyArrow(i: Int) = new {
     |   def ~>(j: Int) = PRange(i, j)
     | }
intWithTildyArrow: (i: Int)java.lang.Object{def ~>(j: Int): PRange}

scala> implicit def prangeWithTildyArrow(p: PRange) = new {
     |   def ~>(step: Int) = p.copy(step = step)
     | }
prangeWithTildyArrow: (p: PRange)java.lang.Object{def ~>(step: Int): PRange}

scala> implicit def pSlice[A](coll: List[A]) = new {
     |   def apply(prange: PRange) = {
     |     import prange._
     |     coll.slice(start, end).grouped(step).toList.map(_.head)
     |   }
     | }
pSlice: [A](coll: List[A])java.lang.Object{def apply(prange: PRange): List[A]}

scala> val xs = List.range(1, 10)
xs: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> xs(3 ~> 9)
res32: List[Int] = List(4, 5, 6, 7, 8, 9)

scala> xs(3 ~> 9 ~> 2)
res33: List[Int] = List(4, 6, 8)

ScalaAPI here

所以不是同样的符号便利,但是操作是存在的

def slice (from: Int, until: Int) : Seq[A]

Selects an interval of elements.

Selects an interval of elements.

Note: c.slice(from, to) is equivalent to (but possibly more efficient than) c.drop(from).take(to - from)

from the index of the first returned element in this sequence. until the index one past the last returned element in this sequence.

returns

a sequence containing the elements starting at index from and extending up to (but not including) index until of this sequence.

definition classes: IterableLike → TraversableLike

Scala中的等效方法(语法略有不同)适用于所有类型的序列:

scala> "Hello world" slice(0,4)
res0: String = Hell

scala> (1 to 10) slice(3,5)
res1: scala.collection.immutable.Range = Range(4, 5)

与Python中的切片相比,最大的区别是在Scala中开始和结束索引是必需的。

相关问题 更多 >