Scala:使用折叠生成Int';s

Scala:使用折叠生成Int';s,scala,folding,Scala,Folding,我正在学习Scala,作为一项作业,我必须使用折叠来生成Int的列表: // Generate list of integers by applying f to b until it returns None def unfold(b: Int, f: Int => Option[(Int, Int)]): IntList = { f(b) match { case None => Nil() case Some((x, y)) => Cons(x,unf

我正在学习Scala,作为一项作业,我必须使用折叠来生成Int的列表:

// Generate list of integers by applying f to b until it returns None
def unfold(b: Int, f: Int => Option[(Int, Int)]): IntList = {
  f(b) match {
    case None => Nil()
    case Some((x, y)) => Cons(x,unfold(y, f))
  }
}
这个展开很好,但现在我必须写一个FromTill,老实说,我完全不知道该怎么做??所以我只是随机开始,但这根本不起作用。我们将非常感谢您的帮助

// generate the list of integers from i until j
def fromUntil(i: Int, j: Int): IntList = {
    unfold(i, (x: Int) =>if(x < j) Some((j, j - 1)) else None)
    }
}
//生成从i到j的整数列表
def FROMTILL(i:Int,j:Int):IntList={
展开(i,(x:Int)=>如果(x

杰罗姆

因为这是一个家庭作业,我不会给你一个完整的答案,只会给你一些线索:

  • 您工作中最困难的部分是定义
    fromUntil
    中的
    f
    函数
  • 看看unfold是如何实现的。特别是非终止案例。这个
    y
    是从哪里来的,它是什么时候计算出来的
  • 你能从你所提供的服务中定义
    f

  • 你走对了方向:

  • 检查
    fromUntil
    的语法是否正确-您有一些额外的大括号
  • 因为它是“从开始到结束”的顺序应该不断增加
  • y
    中的
    unfold
    应该随着每次调用而不断增长
  • 继续,试着看看如果调用
    fromtil(1,1)
    会发生什么,然后如果调用
    fromtil(1,2)
    会发生什么,依此类推。你快到了