Haskell:无法与Int类型[Int]匹配
嗨,这里是我的代码如下。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.
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)
你必须知道自己想要的是什么行为;第一个对我来说似乎最有用。
谢谢你解决我的问题! –
错误只是告诉你有一个太多的(或一个太少)列表层的地方。
你为什么把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]]
类型的结果。
谢谢你的帮助! –
你想在这里做什么 - 你不要添加任何东西! – Carsten
@Carsten我试图获取存储在树的节点中的Ints,并在初始节点之后为树的第一级的每个分支添加每个分数。 –
请粘贴代码片段而不是屏幕截图。 – amalloy