我在scala中有一个Order类型列表。
case class Order(id: String, prod: Product, quantity: Int)
case class Product(id: String, name: String, tasks: List[Task])
我这样做了,我得到了List(List[Task]))
:
val listTaskLists = orders.map(p => p.getProduct().tasks)
现在我想返回一个类型为TaskSchedule的List。此列表将具有的条目数是listTaskLists的大小乘以每个产品的数量。
例如,我有这些条目:
val order1 = new Order("ORD_1", product1, 1) // product1 has 4 tasks
val order2 = new Order("ORD_2", product2, 2) // product2 has 6 tasks
val order3 = new Order("ORD_3", product3, 3) // product3 has 5 tasks
val order4 = new Order("ORD_4", product4, 1) // product4 has 5 tasks
val orders = o1 :: o2 :: o3 :: o4 :: Nil
考虑到这一点,我应该返回一个包含36个条目的TaskSchedule列表:(4个任务* 1个prods)+(6个任务* 2个prods)+(5个任务* 3个prods)+(5个任务* 1 prods)= 36个任务时间表
但我无法这样做。我得到的最接近的是返回一个包含4个任务计划(listTaskLists的大小)的列表:
listTaskLists.map(s => new TaskSchedule(null, 1, 100 minute, 200 minute))
任何人都可以帮助我吗?
答案 0 :(得分:1)
val orders = List(order1, order2, order3, order4) // List[Order]
.map(ord => (ord.prod.tasks, ord.quantity)) // List[(List[Task], Int)]
.flatMap(t => createSchedules(t._1.size * t._2)) // List[TaskSchedule]
def createSchedules(numSchedules: Int): List[TaskSchedule] =
List.fill[TaskSchedule](numSchedules)(new TaskSchedule(null, 1, 100 minute, 200 minute))
修改强>:
orders
可缩短为:
val orders = List(order1, order2, order3, order4)
.flatMap(ord => createSchedules(ord))
def createSchedules(ord: Order): List[TaskSchedule] = {
val numSchedules = ord.prod.tasks.size * ord.quantity
List.fill[TaskSchedule](numSchedules)(new TaskSchedule(null, 1, 100 minute, 200 minute))
}
答案 1 :(得分:0)
如果要迭代一系列事物并使结果列表的长度不同,可以使用fold
// This says that we are folding over the orders list, and turning it into a list of TaskSchedules (starting with an empty list of them)
val taskSchedules = orders.foldLeft(List.empty[TaskSchedule]) { (taskSchedules, currentOrder) =>
// This is where you put your logic for turning the currentOrder into a list of TaskSchedules
val newSchedules: List[TaskSchedule] = ???
// Add these new schedules to the existing ones
taskSchedules ++ newSchedules
}