'forward reference扩展了变量dateList'的定义,同时生成daterange

时间:2013-10-17 16:39:45

标签: scala date recursion

我正在尝试列出scala中两个给定日期之间的所有日期。这是我写的程序:

object testingscala
{
    def main(args: Array[String]) 
    {
       println(calculateDates(LocalDate.of(2014,1,1), LocalDate.of(2014,2,5)))
    }
    def calculateDates(from: LocalDate, until: LocalDate): List[LocalDate] = 
   {
        var arr = List[LocalDate]()
        var dateList = calculateDatesRecur(from, until) // forward reference extends over definition of variable 
 dateList
        def calculateDatesRecur(from: LocalDate, until: LocalDate): List[LocalDate] =
        {
            if (from.compareTo(until) > 1) {return arr}
            else
            { arr = arr :+ from; calculateDatesRecur(from.plusDays(1), until)}
        }
        return dateList

   }

}

我在Scala比较新,所以我无法弄清楚实现有什么问题。 该函数只需要两个参数并打印出两个日期之间的所有日期。我使用了递归。

2 个答案:

答案 0 :(得分:4)

这是因为Scala没有数组/列表的文字语法。你必须使用

 var arr = List.empty[LocalDate]

 var arr = List[LocalDate]()

scala中的列表不是数组

虽然您没有问过,但我相信这段代码可以用更简洁的方式编写:

object testingscala extends App
{
    type LD = LocalDate
    println(calculateDatesRecur(LocalDate.of(2014,1,1), LocalDate.of(2014,2,5)))

    @annotation.tailrec
    def calculateDatesRecur(from: LD, until: LD, xs: List[LD] = List.empty[LD]): List[LD] = 
      if (from.compareTo(until) > 1) xs.reverse
      else calculateDatesRecur(from.plusDays(1), until, from::xs)
}

虽然没有测试过。

并回答您的评论:

交换递归函数和dateList变量,因此函数定义首先出现。

...
def calculateDatesRecur(from: LocalDate, until: LocalDate): List[LocalDate] =
{
  if (from.compareTo(until) > 1) {return arr}
  else
  { arr = arr :+ from; calculateDatesRecur(from.plusDays(1), until)}
}
var dateList = calculateDatesRecur(from, until)
...

你正在尝试分配函数结果,但由于它像嵌套函数一样使用它不知道apriory所以编译器不知道要设置为dateList(实际上它确实知道,但是阻止你做坏事)。

答案 1 :(得分:0)

Given a range, getting all dates within that range in Scala类似

Lamma Date只需(2014, 5, 5) to (2014, 5, 10) foreach println