2012-07-24 39 views
2

我想實現階乘的尾遞歸版本:無法構造無限類型 - 實施尾遞歸階乘計算器

let{factorial 0 n = n; factorial x n = factorial (x-1, n * x)} 

我得到這個:

<interactive>:1:41: 
Occurs check: cannot construct the infinite type: t1 = t1 -> t1 
In the return type of a call of `factorial' 
In the expression: factorial (x - 1, n * x) 
In an equation for `factorial': 
    factorial x n = factorial (x - 1, n * x) 

<interactive>:1:52: 
Occurs check: cannot construct the infinite type: t0 = (t0, t1) 
In the first argument of `(-)', namely `x' 
In the expression: x - 1 
In the first argument of `factorial', namely `(x - 1, n * x)' 

<interactive>:1:61: 
Occurs check: cannot construct the infinite type: t1 = (t0, t1) 
In the second argument of `(*)', namely `x' 
In the expression: n * x 
In the first argument of `factorial', namely `(x - 1, n * x)' 

我如何構建無限類型在這裏? (使用GHCI 7.0.1)

+1

如果您給定義類型簽名,錯誤消息通常更容易理解。你會得到一些與''無法匹配預期類型'Integer'和實際類型'(t0,t1)'''''一致的東西。 – 2012-07-24 20:20:36

回答

7

我不是一個強大的哈斯克爾程序員,但我想你想重寫

factorial x n = factorial (x-1, n * x) 

factorial x n = factorial (x-1) (n * x) 

由於(x-1, n * x)是一雙類型,不是你想要的。

希望這會有所幫助!

+0

當然!儘管知道對,我會責怪我將args傳遞給一個函數的習慣,呃......'非函數式編程方式'? :) – badmaash 2012-07-24 19:42:56