Scala List Comprehensions

4.1k views Asked by At

I'm trying to generate a list in scala according to the formula:

for n > 1 f(n) = 4*n^2 - 6*n + 6 and for n == 1 f(n) = 1

currently I have:

def lGen(end: Int): List[Int] = {
    for { n <- List.range(3 , end + 1 , 2) } yields { 4*n*n - 6*n - 6 }
}

For end = 5 this would give the list:

List(24 , 76)

Right now I'm stuck on trying to find a gracefull way to make this function give

List(1 , 24 , 74)

Any suggestions would be greatly appreciated.

-Lee

2

There are 2 answers

2
fotNelton On BEST ANSWER

How about this:

scala> def lGen(end: Int): List[Int] =
         1 :: List.range(3, end+1, 2).map(n => 4*n*n - 6*n + 6)

scala> lGen(5)
res0: List[Int] = List(1, 24, 76)
2
Luigi Plinge On

I'd separate out the "formula" from the list generation:

val f : Int => Int = {
  case 1 => 1
  case x if x > 1 => 4*x*x - 6*x + 6
}

def lGen(end: Int) = (1 to end by 2 map f).toList

or

def lGen(end: Int) = List.range(1, end + 1, 2) map f