簡體   English   中英

haskell無法構造無限類型

[英]haskell cannot construct the infinite type

我認為以下代碼應該工作:

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)

為什么不編譯?

你需要圍繞遞歸調用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 ,然后將其添加到ii (即i應用於自身),然后減去1。

這是因為函數應用程序在Haskell中具有最高優先級,因此函數應用程序比算術綁定更緊密。

暫無
暫無

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

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