Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create List from Range

I am new to Scala, just started learning, so this is basic beginner question.

I try to implement Sieve of Eratosthenes algorithm. Here is what I got so far:

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))

The result is:

List(2)

As far as I understand, case _ => cross :: Nil is matched in first iteration of sieve_core, which means that crossed is not an instance of a List.

I changed lst parameters type to List[Int] and now the code won't compile with an error:

(fragment of Problem3.scala):24: error: type mismatch;
 found   : Range.Inclusive
 required: List[Int]
    sieve_core(2, (2 to max))
                      ^

Apparently Range is not a List.

Question: how can I turn Range into a List? Or is it some bigger problem with my code, I have made some bad assumption somewhere along the way?

Any help appreciated.

like image 417
Ula Krukar Avatar asked Sep 11 '09 01:09

Ula Krukar


2 Answers

There's an apply method on the List companion object which takes a range and returns a List:

scala> List.range(2, 11)
res0: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)

There are lots of useful List factory methods in the List collection documentation.

like image 149
DigitalRoss Avatar answered Sep 19 '22 21:09

DigitalRoss


To turn any sequence s into a list, use s.toList

I'm sure digitalross' is more efficient in this case, though.

like image 44
Jonathan Graehl Avatar answered Sep 18 '22 21:09

Jonathan Graehl