0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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, i.e. flatten the list. This is just what flatMap does.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.