簡體   English   中英

訪問列表中的下一個元素以在 Scala 中進行比較

[英]Accessing the next element in list to compare in Scala

我是 Scala 的新手,我想知道如何調用列表的下一個元素,因為我正在嘗試將當前元素與相鄰元素進行比較。 給定 x 作為當前元素,我嘗試了類似於 java, x+1 的方法,但是沒有用。 有什么幫助嗎?

for (x <- list; if (x == (next adj. element))) println("same")

滑動呢?

val list = List(1,2,3,4)
list.sliding(2).foreach(println)

//List(1, 2)
//List(2, 3)
//List(3, 4)

for循環中執行此操作的規范方法是:

scala> val xs = List(1,2,3,4,3,2)
xs: List[Int] = List(1, 2, 3, 4, 3, 2)

scala> for (List(left,right) <- xs.sliding(2) if (left < right)) println(left + " < " + right)
1 < 2
2 < 3
3 < 4

scala> for ((left,right) <- (xs zip xs.tail) if (left < right)) println(left + " < " + right)
1 < 2
2 < 3
3 < 4

(順便說一下,在這個例子中,你最好把 if 語句放在 for comprehension 外面而不是里面。)

如果您有索引而不是值,您只需使用相同的模式取消引用它們。 就個人而言,我認為這種模式不是很清楚或有用。 它很慢,有一些奇怪的角落案例,列表未滿,並且很難跟蹤正在發生的事情。 相反,我定義

class PairedIterable[A](it: Iterable[A]) {
  def foreachpair(f: (A,A) => Unit) = {
    val i = it.iterator
    if (i.hasNext) {
      var prev = i.next
      while (!ans && i.hasNext) {
        val x = i.next
        f(prev,x)
        prev = x
      }
    }
  }
}
implicit def iterable_has_pairs[A](it: Iterable[A]) = new PairedIterable(it)

然后可以像這樣使用:

scala> xs.foreachpair((left, right) => if (left < right) println(left + " < " + right))
1 < 2
2 < 3
3 < 4

變體“forallpair”、“existspair”和“findpair”特別有用。

這可以通過遞歸遍歷列表而不是遍歷元素來更好地處理,因為元素對列表一無所知。

例如:

def recurse[T](list: List[T]): Unit = list match {
    case List(x, y, _*) if x == y => 
        println("same")
        recurse(list.tail)
    case Nil =>
    case _   => recurse(list.tail)
}

作為一種選擇,您可以使用match和 recursion 而不是for

object Test {
  def main(args: Array[String]) {
    val list = List(1, 5, 3)
    loop(list)
  }

  def loop(list: List[Int]) {
    list match {
      case Nil => println("Empty list")
      case x :: Nil => println("last " + x)
      case x :: tail => {
        println(x + " - " + tail.head)
        loop(tail)
      }

    }
  }
}
scala> val xs = 1::3::5::4::Nil
xs: List[Int] = List(1, 3, 5, 4)

scala> (xs, xs.tail).zip.foreach(println)
(1,3)
(3,5)
(5,4)

scala>

在 Scala 2.11.7 中,以下內容是有效的:

scala> val xs = List(1,2,3,4)
xs: List[Int] = List(1, 2, 3, 4)

1) 拉上尾巴

scala> xs.zip(xs.tail)
res0: List[(Int, Int)] = List((1,2), (2,3), (3,4))

2)滑動窗口

scala> xs.sliding(2)
res1: Iterator[List[Int]] = non-empty iterator

列表.tail.head

如果要遍歷列表前面的所有元素,則給出下一個元素。 這是因為頭部是最前面的元素,尾部是列表的其余部分。

scala> val li = List (3, 4, 5) 
li: List[Int] = List(3, 4, 5)

scala> li.tail.head 
res74: Int = 4

如果您不想只比較單個元素,而是要比較任意長度的序列,則可以在遞歸函數中進行:

def compAdjectent (l: List [Int]) : Boolean = l match {
  case Nil => false 
  case x :: Nil => false 
  case x :: y :: xs => if (x.equals (y)) true else compAdjectent (y :: xs)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM