2013-09-26 34 views
3

我想下面的代碼應該工作:哈斯克爾無法構造無限類型

sum_up x = loop_it 0 x 
    where loop_it sum i | i > 0  = loop_it sum+i i-1 
         | i == 0 = sum 

但我發現了這個錯誤:

<interactive>:3:15: error: 
    • Occurs check: cannot construct the infinite type: 
     t2 ~ (t0 -> t2) -> t2 
     Expected type: t2 -> t2 
     Actual type: t2 -> (t0 -> t2) -> t2 
    • In an equation for ‘sum_up’: 
      sum_up x 
      = loop_it 0 x 
      where 
       loop_it sum i 
        | i > 0 = loop_it sum + i i - 1 
        | i == 0 = sum 
    • Relevant bindings include 
     loop_it :: t2 -> t2 (bound at <interactive>:3:15) 

爲什麼沒有這個編譯?

回答

6

您需要周圍的遞歸調用的參數括號loop_it

sum_up x = loop_it 0 x 
    where loop_it sum i | i > 0  = loop_it (sum+i) (i-1) -- <- Here 
         | i == 0 = sum 

如果你不組就這樣,編譯器會隱式組這樣的:

((loop_it sum)+(i i))-1 

...這可能不是你想要的,因爲這意味着:「將loop_it應用於sum,然後將其添加到i i(即,將i應用於其本身),然後減去1.

發生這種情況是因爲函數應用程序在Haskell中的優先級最高,所以函數應用程序的綁定比算術更緊密。

+0

該死的這麼簡單的修復,謝謝! – Skyfe

+0

不客氣! –