Scala:线程中的异常" main" java.util.NoSuchElementException:空列表的头

时间:2017-06-10 20:38:02

标签: scala list recursion functional-programming

我有两个这样的Scala列表:

taskProduct: List[(TaskOrder, Product)] = TSK1,PRD1 :: TSK1,PRD2 :. TSK1,PRD3 :: TSK2,PRD1 :: TSK2,PRD2 :: TSK2,PRD3 ::Nil

humanPhysical: List[(Human, Physical)] = H1,PHYS1 :: H1,PHYS2 :: H2,PHYS1 :: H2,PHYS2 :: H3,PHYS3 :: H3,PHYS4 :: H4,PHYS3 :: H4,PHYS4 :: Nil // Physical is a short for Physical Resource

我是编码函数,它将列表taskProduct的每个元素与列表humanPhysical的元素相关联。

taskProduct列表将被迭代,每当算法将相关元素与列表humanPhysical的另一个元素相关联时,taskProduct的这个元素将被丢弃。

在每个周期的最后,如果taskProduct列表中仍有一些元素,则该函数必须再次运行,并且列表humanPhysical将以默认值发送(值为在开始时发送。)

到目前为止我有这个功能:

def createSchedules(taskProduct: List[(TaskOrder, Product)], humanPhysical: List[(Human, Physical)], previousTime: Duration): List[TaskSchedule] = {
    def createSchedules2(taskProduct: List[(TaskOrder, Product)], humanPhysical: List[(Human, Physical)], previousTime: Duration, humanPhysicalOccupied: List[String], Product)]): List[TaskSchedule] = taskProduct match {
      case (a, b) :: tail =>
        val listExistsHuman = humanPhysical.map(x => humanPhysicalOccupied.contains(x._1.id))
        val existsHuman = listExistsHuman.filter(x => x == true).length
        if (existsHuman > 0) println("occupied by human resources")
        else {
          val listExistsPhysical = humanPhysical.map(x => humanPhysicalOccupied.contains(x._2.id))
          val existsPhysical = listExistsPhysical.filter(x => x == true).length
          if (existsPhysical > 0) println("occupied by physical resources")
          else {
            val physicalOfTheHuman = humanPhysical.head._2.post
            val physicalResourcedAcceptedByThisTask = a.physicalRes.map(pr => pr.post)
            if (!physicalResourcedAcceptedByThisTask.contains(physicalOfTheHuman)) println("task doesnt accept physical resource")
            else {
              createSchedules2(tail, humanPhysical.tail, previousTime + a.time, humanPhysical.head._1.id :: humanPhysical.head._2.id :: humanPhysicalOccupied, taskProduct.head :: tasksScheduled)
            }
          }
        }
        createSchedules2(taskProduct, humanPhysical.tail, previousTime + a.time, humanPhysicalOccupied, tasksScheduled)
      case Nil => Nil
    }
    createSchedules2(taskProduct, humanPhysical, 0 minute, List.empty, List.empty)
  }

但这会在Exception in thread "main" java.util.NoSuchElementException: head of empty list行显示错误:val physicalOfTheHuman = humanPhysical.head._2.post

我应该对我的解决方案做些什么调整才能使其正常工作?

0 个答案:

没有答案