Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala List Comprehensions

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

like image 832
LeeG Avatar asked Jan 26 '12 05:01

LeeG


1 Answers

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
like image 197
Luigi Plinge Avatar answered Nov 11 '22 20:11

Luigi Plinge