Scala中的切片表示法? [英] Slice notation in Scala?

查看:29
本文介绍了Scala中的切片表示法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala中是否有类似于the slice notation in Python的内容?

我认为这确实是一个有用的操作,应该合并到所有语言中。

推荐答案

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)

这篇关于Scala中的切片表示法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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