【问题标题】:How to map list items with their tail [Scala]如何用尾巴映射列表项[Scala]
【发布时间】:2021-02-12 03:36:44
【问题描述】:

如何迭代地映射列表中的每个项目及其剩余的尾部?伪代码示例:

val list = List(1,2,3,4) 
list.foreach((head, tail) => println(s"head= $head, tail= $tail")) 
// head= 1, tail = List(2, 3, 4) 
// head= 2, tail = List(3, 4) 
// head= 3, tail = List(4) 
// head= 4, tail = List()

【问题讨论】:

  • 模式匹配@tailrec?还是您在寻找其他东西?
  • 可能是tails?正如我常说的,scaladoc 是你的朋友。

标签: scala functional-programming scala-collections


【解决方案1】:

最简单的方法似乎是旧的for-loop,它的优点是它为您插入了一个过滤步骤,因此您在迭代尾部时不会在Nil 情况下崩溃:

for (h :: t <- (1 to 4).toList.tails) println(s"head: $h tail: $t")

给予:

head: 1 tail: List(2, 3, 4)
head: 2 tail: List(3, 4)
head: 3 tail: List(4)
head: 4 tail: List()

如果您实际上不需要 println 副作用,for-yield 将只为您提供值。

【讨论】:

    【解决方案2】:
    def rec(l: List[Int]) : Unit = {
        l match {
            case head::tail => println(s"head= $head, tail= $tail")
                rec(tail)
            case _ =>
        }
    }
    
    scala> rec(l)
        head= 1, tail= List(2, 3, 4)
        head= 2, tail= List(3, 4)
        head= 3, tail= List(4)
        head= 4, tail= List()
    

    【讨论】:

      【解决方案3】:

      一个(对我来说)更直接的答案。正如@LuisMiguelMejíaSuárez 所说,尾巴是你的朋友

      (xs zip xs.tails.toList) map {case (h, t) => println("Head: " + h + " Tail: " + t)}
      

      .toList 很可惜


      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-19
        • 2010-10-27
        • 1970-01-01
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        相关资源
        最近更新 更多