user_123945839432
user_123945839432

Reputation: 189

Challenge in building a list in scala recursively

How to write a function, which builds a list of the given length. Each element is determined by applying f to the index of the element:

def buildList[A](length: Int, f: Int => A): List[A]

test case would be something like this:

test("test") {
def f(x: Int) = x
assert(buildList(10, f) == List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) 

So an input example would be listBuild(10,f) = output List(0,....9)

I'd know how to do this in OOL but functioning programming is a somewhat new concept to me.

Any ideas on how to accomplish this? At least, the pseudo code would help..

PS: This is not HW. I have been trying to teach myself scala and this is a function I have been struggling with...

Upvotes: 2

Views: 2599

Answers (5)

BOliver
BOliver

Reputation: 1

I think this is the most simple and elegant recursion list generation :

def listBuilder(iterate : Int): List[Int] = {
  if(iterate == 0) List() :+ 0
  else  listBuilder(iterate-1) :+ iterate
}

Upvotes: 0

Julien__
Julien__

Reputation: 2028

  1. k is an Integer and will never match against the empty list Nil.
  2. Here is your function, use "buildLister"

    def listBuilder[A](k:Int, f:Int=>A) : List[A] = if( k < 0 ) Nil else f(k) :: listBuilder(k-1, f)

    def buildLister[A](k:Int, f:Int=>A) : List[A] = listBuilder(k-1, f).reverse

Upvotes: 0

building a list in scala recursively

You can try something like this:

object UtilList {

  def build[A](length: Int, f: Int => A): List[A] = {
    val list: List[A]= List()

    @annotation.tailrec
    def foo(list: List[A], index: Int, f: Int => A): List[A] = {
      if (index == length) list
      else foo(f(index) :: list, index + 1, f)
    }
    foo(list, 0, f)
  }
}

Upvotes: 1

Karl Bielefeldt
Karl Bielefeldt

Reputation: 48998

It's preferable not to use recursion here. You can get a sequence containing the indexes using a Range. Applying a function to every element of a collection is called a map. Combining the two gives you:

0 until length map f

Upvotes: 2

Kevin Meredith
Kevin Meredith

Reputation: 41909

scala> def buildHelper(x: Int): List[Int] = 
     |  if (x < 0) List() else x :: buildHelper(x-1)
buildHelper: (x: Int)List[Int]

scala> def buildList(x: Int): List[Int] = 
     |   ???
buildList: (x: Int)List[Int]

Implementation for buildList (scroll over it to view it - but I'd try to implement it first on your own):

buildHelper(x).reverse

scala> buildList(10)
res2: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Upvotes: 0

Related Questions