Paweł Jaworowski
Paweł Jaworowski

Reputation: 253

How to set changed list as argument

I don't get adding elements to list in Scala. I can't use mutable lists and I saw examples where it is possible to add elements to immutable, but it doesn't work in my case. Ok, so my code is simple function. It is returning list of powers.

def power_fun ( number : Int, power: Int ) : List[Int] = {

    def power_list( number_tmp : Int, 
                    power_tmp : Int, 
                    list_tmp : List[Int] ) : List[Int] = {

        if(power != 0) {
           power_list( number_tmp * number_tmp, 
                       power_tmp - 1, 
                       list_tmp :: number_tmp ) // this return error "value :: not member of Int)
        }
        else
           return list_tmp
    }
    return power_list(number, power, List[Int]())
}

I can't figure out how to add element to the list. Could you help me, how to set changed list (with new elem) as argument?

Upvotes: 0

Views: 62

Answers (1)

Shyamendra Solanki
Shyamendra Solanki

Reputation: 8851

list_tmp :: number_tmp

It does not work because the :: method is right associative, so requires list on the right hand side. All methods that ends with : are right associative.

There are different ways to add an element to the list.

number_tmp :: list_tmp  // adds number_tmp at start of new list.

list_tmp :+ number_tmp  // appends at the end of the list. 

number_tmp +: list_tmp  // adds number at the start of the list.

scala> val l = List(1, 2)
l: List[Int] = List(1, 2)

scala> l :+ 3 // append
res1: List[Int] = List(1, 2, 3)

scala> 3 +: l   // prepend
res2: List[Int] = List(3, 1, 2)

scala> 3 :: l   // prepend
res3: List[Int] = List(3, 1, 2)

scala> l.::(3) // or you can use dot-style method invocation
res4: List[Int] = List(3, 1, 2)

Upvotes: 3

Related Questions