2015-07-22 32 views
1

我學習Scala的個人興趣,我通過以下的返回值困惑:關於斯卡拉* =運算符的返回值

var t : Long = 1 
def product(s:String):Long = { 
    if(s.length > 1) t *= product(s.tail) 
    else t *= s.toLong 
} 

這是一個遞歸函數,但是編譯器高大我有兩個錯誤:

<console>:13: error: type mismatch; 
found : Unit 
required: Long 
     if(s.length > 1) t *= product(s.tail) 
         ^
<console>:14: error: type mismatch; 
found : Unit 
required: Long 
     else t *= s.toLong 
      ^

和在scala-doc中,我找不到def * = in Long。

+0

什麼是't'?它在哪裏定義? – dhg

+0

對不起var t:長= 1 –

回答

2

t *= product(s.tail)t = t * product(s.tail)

如果你想返回的T他值速記,你必須做明確:

var t : Long = 1 
def product(s:String):Long = { 
    if(s.length > 1) t *= product(s.tail) 
    else t *= s.toLong 

    t 
} 

但看到你副作用的這裏T,它不是真正在功能編程的精神。

我更喜歡一個純函數:

def product(s:String, t: Long):Long = { 
    if(s.length > 1) t * product(s.tail, t) 
    else t * s.toLong 
} 
+0

可能有一個很好的理由使用可變變量。沒有足夠的上下文來說明這一點,國際海事組織。 – ReyCharles

+0

'product'的遞歸調用在這裏不正確,它應該有兩個參數,比如'product(s.tail,t)' – GSPdibbler

0

t *= …,如果不超載,爲t = t * …的簡寫 - 一個簡單的分配新建分配FY。由於這些have Unit return type而不是產生新的值(Long),您在這裏(兩次)得到一個類型錯誤。

改變你的函數下面應該工作:

def product(s:String): Long = { 
    t *= if(s.length > 1) product(s.tail) else s.toLong 
    t 
} 

但是你應該要麼改變返回類型Unit,如果你只關心改變t反正副作用:

var t: Long = 1 
def product(s:String): Unit = { 
    t *= if(s.length > 1) product(s.tail) else s.toLong 
} 

或使功能純粹而不變異變量:

val t: Long = 1 
def product(s:String): Long = 
    t * if(s.length > 1) product(s.tail) else s.toLong 
1

x *= e構建體返回(用 「=」 符號)Unit

scala> var t : Long = 1 
t: Long = 1 

scala> :type t *= 42 
Unit 

scala> 
0

分配表達沒有返回,這是我們可以稱之爲UnitScala

*=意味着*首先,然後進行分配。因此,您實際上返回Unit,而不是長。

0

當您使用表達式*=時,您正在創建一個修改左側變量的副作用,在此例中爲t。由於其本身的副作用沒有返回值,因此Scala編譯器會告訴您類型不匹配,具體而言,Unit不符合Long

由於t執行所需的值,其中product修改tt需要由product明確地返回。將它放在最後一行使其成爲返回值(Scala不需要編寫return t,但是您可以;它相當於任何一種方式)。其他已經發布了補丁,但在這樣的情況下,可以考慮這樣做:

var t : Long = 1 
def product(s:String) = { 
    if(s.length > 1) t *= product(s.tail) 
    else t *= s.toLong 
    t //Made t the return, which is what you want. 
} 

和合作,通過您的定義從那裏。這不會編譯,但它會向您顯示下一步。想想在所有情況下如何使product返回t。仔細想想你如何使用遞歸。