访问列表中的下一个元素以在 Scala 中进行比较

发布于 2024-11-02 10:10:26 字数 196 浏览 0 评论 0原文

我是 Scala 新手,我想知道如何调用列表的下一个元素,因为我正在尝试将当前元素与相邻元素进行比较。 给定 x 作为当前元素,我尝试了类似于 java, x+1 但那不起作用。有什么帮助吗?

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

I'm new to Scala and i was wondering how you can call the next element of the list because I am trying to compare the current element with the adjacent one.
Given x as the current element, I tried similar to java, x+1 but that didnt work. Any help?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

森罗 2024-11-09 10:10:26

滑动怎么样?

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

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

How about sliding?

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

//List(1, 2)
//List(2, 3)
//List(3, 4)
千紇 2024-11-09 10:10:26

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 理解的外部而不是内部。)

如果您有索引的值,您只需使用相同的模式取消引用它们即可。就我个人而言,我认为这种模式不是很清晰或有用。它很慢,有奇怪的极端情况,列表不完整,而且很难跟踪正在发生的事情。相反,我定义了

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”特别有用。

The canonical ways to do this in a for loop would be:

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

(Incidentally, you're probably better off putting the if statement outside rather than inside the for comprehension in this example.)

If you have indices instead of values, you just dereference them using the same pattern. Personally, I don't find this pattern very clear or useful. It's slow, has weird corner-cases with lists that aren't full, and it's hard to follow what's going on. Instead, I define

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)

which can then be used like so:

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

Variants "forallpair", "existspair", and "findpair" are particularly useful.

隔纱相望 2024-11-09 10:10:26
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> 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>
萌逼全场 2024-11-09 10:10:26

作为一个选项,您可以使用 match 和递归来代替 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)
      }

    }
  }
}

As an option you may use match and recursion instead of 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)
      }

    }
  }
}
甜嗑 2024-11-09 10:10:26

通过在列表上递归而不是在元素上迭代可以更好地处理这个问题,因为元素对列表一无所知。

例如:

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)
}

This would be better handled by recursing over the list, instead of iterating through the elements, since elements don't know anything about the list.

For example:

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)
}
刘备忘录 2024-11-09 10:10:26

与 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

As in Scala 2.11.7 the following are valid:

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

1) Zip the tail

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

2) Slide the window

scala> xs.sliding(2)
res1: Iterator[List[Int]] = non-empty iterator
白衬杉格子梦 2024-11-09 10:10:26

list.tail.head

如果您想遍历列表前面的所有元素, 会给出下一个元素。这是因为 head 是最前面的元素,tail 是列表的其余部分。

list.tail.head

gives the next element if you want to go through all the elements from the front of the list. This is because the head is the front-most element and tail is the rest of the list.

粉红×色少女 2024-11-09 10:10:26
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)
}
scala> val li = List (3, 4, 5) 
li: List[Int] = List(3, 4, 5)

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

If you don't want to compare just a single element, but a sequence of arbitrary length, you can do it in recursive function:

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)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文