I'm trying to write a function that takes multiple lists as input and returns a list of strings representation of every combination between those lists.
Sample Input:
val integers = List(1,2,3,4)
val characters = List('a','b','c')
val strings = List("apple","grapefruit")
Sample Output:
("1-a-apple", "1-a-grapefruit", .....)
Here is what I have so far:
def main(args: Array[String]): Unit = {
val integers = List(1,2,3,4)
val characters = List('a','b','c')
val strings = List("apple","grapefruit")
val lists = List(integers, characters, strings)
println(generator(lists).toString())
}
//using list api
def generator(x: List[List[Any]]): List[List[Any]] = x match {
case Nil => List(Nil)
case h :: _ => h.flatMap(i => generator(x.tail).map(i :: _))
}
And here is the output of my code:
List(List(1, a, apple), List(1, a, grapefruit), List(1, b, apple), List(1, b, grapefruit), List(1, c, apple), List(1, c, grapefruit), List(2, a, apple), List(2, a, grapefruit), List(2, b, apple), List(2, b, grapefruit), List(2, c, apple), List(2, c, grapefruit), List(3, a, apple), List(3, a, grapefruit), List(3, b, apple), List(3, b, grapefruit), List(3, c, apple), List(3, c, grapefruit), List(4, a, apple), List(4, a, grapefruit), List(4, b, apple), List(4, b, grapefruit), List(4, c, apple), List(4, c, grapefruit))
So my questions are:
1)How can I get the output to be a list of strings instead of list of list of any?
2)How can I use a for comprehension instead of the list api?
val integers = List(1,2,3,4)
val characters = List('a','b','c')
val strings = List("apple","grapefruit")
for {
int <- integers
chars <- characters
string <- strings
} yield { s"${int}-${chars}-${string}" }
That code outputs
val res4: List[String] = List(1-a-apple, 1-a-grapefruit, 1-b-apple, 1-b-grapefruit, 1-c-apple, 1-c-grapefruit, 2-a-apple, 2-a-grapefruit, 2-b-apple, 2-b-grapefruit, 2-c-apple, 2-c-grapefruit, 3-a-apple, 3-a-grapefruit, 3-b-apple, 3-b-grapefruit, 3-c-apple, 3-c-grapefruit, 4-a-apple, 4-a-grapefruit, 4-b-apple, 4-b-grapefruit, 4-c-apple, 4-c-grapefruit)
Here's I'm using string interpolation (eg s" variable is $var1"
) to turn the items into strings.
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.