문제

I have the following:

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

I'm trying to define a function that will move over a val of type Alpha Int and sum it. My desired approach is to extract all the Ints and then sum the resulting list, but I am struggling to extract all the Ints as I don't know what to do with the recursion...

a slight attempt:

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

Obviously this doesn't quite work but I can't see a solution in sight.

도움이 되었습니까?

해결책

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.

다른 팁

You could consider using Tree instead of Alpha, which has many handy operations:

> flatten $ Node 1 [Node 2 [], Node 5 [Node 7 []]]
[1,2,5,7]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top