2016-05-03 45 views
1

我正在做一個代碼來找出一個列表的長度,使用遞歸,但有很多錯誤。我是一個初學者,我不能很好的Haskell。 下面是代碼:如何更好地查找列表長度的代碼?

longListe :: [a] -> a 

longListe [] = error "Empty liste" 
longListe [x]= 1 
longListe n = 1 + longListe (n-1) 
main = print $ longListe 

和錯誤:

No instance for (Num a) arising from the literal ‘1’ 
    Possible fix: 
     add (Num a) to the context of 
     the type signature for longListe :: [a] -> a 
    In the expression: 1 
    In an equation for ‘longListe’: longListe [x] = 1 

4-1-a.hs:6:31: 
    No instance for (Num [a]) arising from a use of ‘-’ 
    In the first argument of ‘longListe’, namely ‘(n - 1)’ 
    In the second argument of ‘(+)’, namely ‘longListe (n - 1)’ 
    In the expression: 1 + longListe (n - 1) 

4-1-a.hs:7:8: 
    No instance for (Show ([a0] -> a0)) 
     (maybe you haven't applied enough arguments to a function?) 
     arising from a use of ‘print’ 
    In the expression: print 
    In the expression: print $ longListe 
    In an equation for ‘main’: main = print $ longListe 

有人可以幫我。謝謝

+0

一個問題:你正在做'(n-1)'哪裏'n'是一個列表。您不能在列表上執行整數操作。 – dvaergiller

+1

爲什麼'longListe'會產生一個錯誤,而不是爲空列表返回0? – chepner

回答

5

問題在於你的函數的類型定義:longListe :: [a] -> a

它工作正常,如果你打電話給號碼列表longListe。例如,如果您撥打longListe [1,2,3],輸入內容將爲[Int] -> Int

但是,如果您嘗試獲取字符串列表的長度,則此類型將變爲[String] -> String。這是而不是你想要什麼,因爲你想返回一個數字。

你得到的錯誤表明:

沒有實例(民一)從字面所產生的「1」

既然你返回一個數字,並與你輸入數字運算,編譯器期望a是一個數字,因此錯誤提及(Num a)

如果您將定義更改爲longListe :: [a] -> Int,它應該會更好(實際上它仍然無法正常工作,但出於其他原因,但我會讓您嘗試自行解決此問題,因爲這是學習的最佳方式) 。

此外,是否有任何理由爲什麼空列表應該錯誤,而不是返回0?

+0

嗯現在來這個錯誤 – posh

+0

4-1-a.hs:3:16: 未能與實際類型'[Char]'匹配預期類型'Int'在表達式中:「空聆聽」 在方程 'longListe':longListe [] = 「空清單當然」 4-1-a.hs:6:8: 沒有實例(顯示([A0] - >智力)) (也許你還沒有使用'print' 在表達式中:print 在表達式中:print $ longListe 在'main'的等式中:main = : 沒有。 – posh

+1

@posh我假設你在'longListe [] = error「空聽」中刪除'error'。您現在在返回類型之間有差異。有時你會返回一個數字,有時候會返回一個字符串('[Char]'相當於'String')。您需要確保您返回的值始終是相同的類型。 –