简体   繁体   中英

Concatenating multiple lists in Scala

I have a function called generateList and concat function as follows. It is essentially concatenating lists returned by the generateList with i starting at 24 and ending at 1

 def concat(i: Int, l: List[(String, Int)]) : List[(String, Int)] = {
          if (i==1) l else l ::: concat(i-1, generateList(signs, i))
 }
 val all = concat(23, generateList(signs, 24))

I can convert this to tail-recursion. But I am curious if there a scala way of doing this?

There are many ways to do this with Scala's built in methods available to Lists.

Here is one approach that uses foldRight

(1 to 24).foldRight(List[Int]())( (i, l) => l ::: generateList(i))

Starting with the range of ints you use to build separate lists, it concats the result of generateList(i) to the initial empty list.

Here is one way to do this:

val signs = ""
def generateList(s: String, n: Int) = n :: n * 2 :: Nil


scala> (24 to 1 by -1) flatMap (generateList(signs, _))
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(24, 48, 23, 46, 22, 44, 21, 42, 20, 40, 19, 38, 18, 36, 17, 34, 16, 32, 15, 30, 14, 28, 13, 26, 12, 24, 11, 22, 10, 20, 9, 18, 8, 16, 7, 14, 6, 12, 5, 10, 4, 8, 3, 6, 2, 4, 1, 2)

What you want to do is to map the list with x => generateList(signs, x) function and then concatenate the results, ie flatten the list. This is just what flatMap does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM