6

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

LeeG
  • 265
  • 1
  • 4
  • 11

2 Answers2

13

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
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
5

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)
fotNelton
  • 3,844
  • 2
  • 24
  • 35