2011-03-23 24 views
3

我已經寫了類似LISP的flatten功能:HUnit TestCase的一個類型錯誤

data NestedList a = Elem a | List [NestedList a] 

flatten :: NestedList a -> [a] 
flatten (Elem x) = [x] 
flatten (List xs) = concatMap flatten xs 

這兩個測試案例很好地工作:

test1 = TestCase (assertEqual "test singleton" [5] (flatten (Elem 5))) 
test2 = TestCase (assertEqual "test mixed" 
           [1,2,3,4] 
           (flatten (List [Elem 1, 
               List [Elem 2, Elem 3], 
               Elem 4]))) 

但是這一個報告類型錯誤:

test3 = TestCase (assertEqual "test empty" [] (flatten (List []))) 

從REPL測試工作正常:

*Main> [] == flatten (List []) 
True 

爲什麼我得到一個錯誤,以及如何爲空列表編寫測試用例?

編輯:這裏是確切的錯誤信息:

Ambiguous type variable `a0' in the constraints: 
    (Show a0) arising from a use of `assertEqual' 
      at D:\haskell\source.hs:61:19-29 
    (Eq a0) arising from a use of `assertEqual' 
      at D:\haskell\source.hs:61:19-29 
Probable fix: add a type signature that fixes these type variable(s) 
In the first argument of `TestCase', namely 
    `(assertEqual "test empty" [] (flatten (List [])))' 
+0

什麼是確切的錯誤信息? – fuz 2011-03-23 20:09:45

+0

@FUZxxl添加錯誤消息 – dbyrne 2011-03-23 20:15:04

+0

此嵌套列表結構通常稱爲玫瑰樹。 – 2011-03-23 21:12:49

回答

7

我猜問題是編譯器無法弄清楚空單的類型。它可能是[Int],[Char],什麼都沒有。嘗試給它一些類型,哪種類型無關緊要。

test3 = TestCase (assertEqual "test empty" ([] :: [Int]) (flatten (List [])))

注意,在其他情況下,編譯器可以推斷列表的類型。

+0

這是「西部最快的槍」...... – fuz 2011-03-23 20:30:11

2

由於錯誤消息已經告訴您,您必須在單元測試中的列表中添加類型簽名。可能是這樣的:

test3 = TestCase (assertEqual "test empty" ([]::[()]) (flatten (List []))) 
相關問題