簡體   English   中英

如何將更改列表設置為參數

[英]How to set changed list as argument

我沒有在Scala中將元素添加到列表中。 我不能使用可變列表,我看到了可以將元素添加到不可變的示例,但在我的情況下不起作用。 好的,所以我的代碼很簡單。 它正在返回權力列表。

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]())
}

我不知道如何將元素添加到列表中。 您能幫我,如何將更改的列表(帶有新的elem)設置為參數?

list_tmp :: number_tmp

因為::方法是正確的關聯,所以它不起作用,因此需要在右側列出。 所有以:結尾的方法都是正確的關聯。

有多種方法可以將元素添加到列表中。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM