2016-03-05 135 views
-2

嗨,這裏是我的代碼如下。Haskell:無法與Int類型[Int]匹配

data Treeof a = Node Int a [Treeof a] deriving (Eq,Show) 

add_score :: Int -> Treeof a -> [[Int]] 
add_score 0 (Node i a xs) = [[0]] 
add_score n (Node i a xs) = [i]:[(map (add_score (n-1)) xs)] 

我試圖獲取存儲在樹中每個節點的詮釋,並將其存儲在一個列表的列表,但得到如下所示的錯誤,我不能確定這是爲什麼。

Couldn't match type `[[Int]]' with `Int' 
    Expected type: Treeof a -> Int 
     Actual type: Treeof a -> [[Int]] 
    In the first argument of `map', namely `(add_score (n - 1))' 
    In the expression: (map (add_score (n - 1)) xs) 
Failed, modules loaded: none. 

編輯:更改[I]:[(地圖(add_score第(n-1))XS)]至[I] :(圖(add_score第(n-1))XS)

而得到一個類似的錯誤

Couldn't match type `[Int]' with `Int' 
    Expected type: Treeof a -> [Int] 
     Actual type: Treeof a -> [[Int]] 
    In the first argument of `map', namely `(add_score (n - 1))' 
    In the second argument of `(:)', namely 
     `(map (add_score (n - 1)) xs) 
Failed, modules loaded: none. 
+1

你想在這裏做什麼 - 你不要添加任何東西! – Carsten

+0

@Carsten我試圖獲取存儲在樹的節點中的Ints,並在初始節點之後爲樹的第一級的每個分支添加每個分數。 –

+2

請粘貼代碼片段而不是屏幕截圖。 – amalloy

回答

4

xs有型號[TreeOf a]。很明顯,你可以用add_score (n-1)映射到這樣一個列表中,因爲這需要TreeOf a作爲參數。

但結果如何?那麼,無論單個add_score (n-1)的結果如何。但這已經是[[Int]],所以你得到了

map (add_score $ n-1) xs :: [ [[Int]] ] 

這是一個嵌套級別太多。現在將它包裝在另一個單例列表中顯然會適得其反。相反,您需要平整一個列表級別。至少有三種方法可以做到這一點:

  • 連接外部列表。

    [i] : (concat $ map (add_score $ n-1) xs) 
    

    這可以很好地更寫有=<<(又名concatMap),作爲

    [i] : (add_score (n-1) =<< xs) 
    
  • 級聯這些列表。

    [i] : (map (concat . add_score (n-1)) xs) 
    
  • 總結最內層的列表。

    [i] : (map (map sum . add_score (n-1)) xs) 
    

你必須知道自己想要的是什麼行爲;第一個對我來說似乎最有用。

+0

謝謝你解決我的問題! –

2

錯誤只是告訴你有一個太多的(或一個太少)列表層的地方。

你爲什麼把map ...作爲列表中的單個元素:

[(map (add_score (n-1)) xs)] 

乍一看,似乎你想要的:

(map (add_score (n-1)) xs) 

但後來因爲add_source充分應用產生了[[Int]],映射它將是類型[[[Int]]](謝謝@Carsten)。您可能在:

concatMap (add_score (n-1)) xs 

這將連接列表併產生[[Int]]類型的結果。

+0

謝謝你的幫助! –

相關問題