1

我有以下内容:

data Alpha a = Beta a [Alpha a]
val = Beta 1 [Beta 2 [], Beta 5 [Beta 7 []]]

我正在尝试定义一个函数,该函数将移动 Alpha Int 类型的 val 并将其求和。我想要的方法是提取所有 Ints,然后对结果列表求和,但我正在努力提取所有 Ints,因为我不知道如何处理递归......

轻微的尝试:

checkAlpha :: Alpha Int -> [Int]
checkAlpha (Beta a []) = [a]
checkAlpha (Beta a b) = [a] ++ (map checkAlpha b)

显然这不太有效,但我看不到解决方案。

4

2 回答 2

7

If you used

concatMap :: (a -> [b]) -> [a] -> [b]

instead of map, it would work and be elegant enough.

You don't need to treat the case of an empty list as second component specially,

checkAlpha :: Alpha a -> [a]
checkAlpha (Beta a alphas) = a : concatMap checkAlpha alphas

does what you want, and is independent of the parameter type.

于 2012-05-04T22:51:12.617 回答
0

您可以考虑使用Tree而不是Alpha,它有许多方便的操作:

> flatten $ Node 1 [Node 2 [], Node 5 [Node 7 []]]
[1,2,5,7]
于 2012-05-05T01:33:52.397 回答