我是Scala的新手,刚刚开始学习,所以这是一个基本的初学者问题.
我尝试实现Sierat of Eratosthenes算法.这是我到目前为止所得到的:
def sieve_core(cross: Int, lst: Seq[Int]): List[Int] = { val crossed = lst.filter(_ % cross != 0) crossed match { case a :: rest => cross :: sieve_core(a, crossed) case _ => cross :: Nil } } def sieve(max: Int): List[Int] = { sieve_core(2, (2 to max)) } println(sieve(100))
结果是:
List(2)
据我所知,case _ => cross :: Nil
在第一次迭代中匹配sieve_core
,这意味着它crossed
不是List的实例.
我将lst
参数类型更改为List[Int]
,现在代码将无法编译并显示错误:
(fragment of Problem3.scala):24: error: type mismatch; found : Range.Inclusive required: List[Int] sieve_core(2, (2 to max)) ^
显然Range
不是一个List
.
问题:如何将Range转换为List?或者我的代码是一个更大的问题,我在某个地方做了一些不好的假设?
任何帮助赞赏.
Dig*_*oss 32
apply
在List
伴随对象上有一个方法,它接受一个范围并返回一个List
:
scala> List.range(2, 11)
res0: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
Run Code Online (Sandbox Code Playgroud)
有很多有用的List
工厂方法中List
采集文件.
归档时间: |
|
查看次数: |
14050 次 |
最近记录: |