当前位置: 动力学知识库 > 问答 > 编程问答 >

Iterating or Pattern Matching a element that may have inner lists in Scala

问题描述:

I have the following structure:

case class Something( name: String, more: List[Something] )

Now, you can imagine, that I want to go over all possible elements in this "Tree"

How to do it? I want to perform a Side effect over this structure:

Something("some", List( Something("someMore", Nil), Something("momoMore", Nil), Something("nowIwantToSee", List( ...... a lot more something )) ))

And this could go into more and more nesting structures....

???

网友答案:

Use recursion:

def recurse(something: Something): Unit = {
  println(something.name)
  something.more.foreach(recurse)
}

So:

> val something = Something("some", List( Something("someMore", Nil), Something("momoMore", Nil), Something("nowIwantToSee", Nil)))
> recurse(something)
some
someMore
momoMore
nowIwantToSee
网友答案:

@Jean Logeart has provided a solution that works. Only problem I see is that the function is not tail recursive. You can test that with @tailrec annotation.

You can use pattern matching here as follow:

def traverse(something: Something): Unit = {
    println(something.name)
    something match {
      case Something(name, Nil) =>
      case Something(name, x :: Nil) => traverse(x)
      case Something(name, x :: xs) => traverse(Something(x.name, xs))
    }
  }
分享给朋友:
您可能感兴趣的文章:
随机阅读: