Tobi3
Tobi3

Reputation: 147

Haskell algebraic data type pattern matching

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.

Upvotes: 1

Views: 972

Answers (2)

Daniel Wagner
Daniel Wagner

Reputation: 153172

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]

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183978

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.

Upvotes: 7

Related Questions