Scala:使用折叠生成Int';s
我正在学习Scala,作为一项作业,我必须使用折叠来生成Int的列表: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
// 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
函数y
是从哪里来的,它是什么时候计算出来的f
你走对了方向:
fromUntil
的语法是否正确-您有一些额外的大括号y
中的unfold
应该随着每次调用而不断增长fromtil(1,1)
会发生什么,然后如果调用fromtil(1,2)
会发生什么,依此类推。你快到了