Knu*_*daa 16 collections scala
鉴于例如:
List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
Run Code Online (Sandbox Code Playgroud)
我想去:
List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))
Run Code Online (Sandbox Code Playgroud)
我会假设有一个简单的List函数来执行此操作,但我无法找到它.
Kev*_*ght 16
这是我通常使用的技巧:
def split[T](list: List[T]) : List[List[T]] = list match {
case Nil => Nil
case h::t => val segment = list takeWhile {h ==}
segment :: split(list drop segment.length)
}
Run Code Online (Sandbox Code Playgroud)
实际上......不是,我通常会对集合类型进行抽象,并使用尾递归进行优化,但希望保持简单的答案.
val xs = List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
Run Code Online (Sandbox Code Playgroud)
这是另一种方式.
(List(xs.take(1)) /: xs.tail)((l,r) =>
if (l.head.head==r) (r :: l.head) :: l.tail else List(r) :: l
).reverseMap(_.reverse)
Run Code Online (Sandbox Code Playgroud)
该死的雷克斯克尔,写下我想要的答案.由于存在轻微的风格差异,这是我的看法:
list.tail.foldLeft(List(list take 1)) {
case (acc @ (lst @ hd :: _) :: tl, el) =>
if (el == hd) (el :: lst) :: tl
else (el :: Nil) :: acc
}
Run Code Online (Sandbox Code Playgroud)
由于元素相同,我没有打扰逆转子列表.
list.foldRight(List[List[Int]]()){
(e, l) => l match {
case (`e` :: xs) :: fs => (e :: e :: xs) :: fs
case _ => List(e) :: l
}
}
Run Code Online (Sandbox Code Playgroud)
要么
list.zip(false :: list.sliding(2).collect{case List(a,b) => a == b}.toList)
.foldLeft(List[List[Int]]())((l,e) => if(e._2) (e._1 :: l.head) :: l.tail
else List(e._1) :: l ).reverse
Run Code Online (Sandbox Code Playgroud)
[编辑]
//find the hidden way
//the beauty must be somewhere
//when we talk scala
def split(l: List[Int]): List[List[Int]] =
l.headOption.map{x => val (h,t)=l.span{x==}; h::split(t)}.getOrElse(Nil)
Run Code Online (Sandbox Code Playgroud)
我在处理集合方法时有这些实现.最后,我检查了更简单的inits和tails实现,并省略了集群.无论多么简单,每种新方法最终都会收取很难从外部看到的大税.但这是我没有使用的实现.
import generic._
import scala.reflect.ClassManifest
import mutable.ListBuffer
import annotation.tailrec
import annotation.unchecked.{ uncheckedVariance => uV }
def inits: List[Repr] = repSequence(x => (x, x.init), Nil)
def tails: List[Repr] = repSequence(x => (x, x.tail), Nil)
def cluster[A1 >: A : Equiv]: List[Repr] =
repSequence(x => x.span(y => implicitly[Equiv[A1]].equiv(y, x.head)))
private def repSequence(
f: Traversable[A @uV] => (Traversable[A @uV], Traversable[A @uV]),
extras: Traversable[A @uV]*): List[Repr] = {
def mkRepr(xs: Traversable[A @uV]): Repr = newBuilder ++= xs result
val bb = new ListBuffer[Repr]
@tailrec def loop(xs: Repr): List[Repr] = {
val seq = toCollection(xs)
if (seq.isEmpty)
return (bb ++= (extras map mkRepr)).result
val (hd, tl) = f(seq)
bb += mkRepr(hd)
loop(mkRepr(tl))
}
loop(self.repr)
}
Run Code Online (Sandbox Code Playgroud)
[编辑:我忘了其他人不会知道内幕.此代码是从TraversableLike内部编写的,因此它不会开箱即用.]
| 归档时间: |
|
| 查看次数: |
6501 次 |
| 最近记录: |