[Haskell] Trying to get a Composite design pattern to work

Greg Buchholz haskell at sleepingsquirrel.org
Mon Mar 13 16:51:51 EST 2006


Asfand Yar Qazi wrote:
> I'm trying to implement hierarchical states in Haskell, following on from my
> work at doing them in C++.
> 
> Here's what I've got so far:
> 
> data StateNode a        = CompositeState [ StateNode a ] | State a
> stateslist :: StateNode a -> [a]
> stateslist(State x) = [x]
> stateslist(CompositeState xs) = {- return list of objects of type a -}
> 
> The following give errors (as they should)
> -- stateslist(CompositeState xs) = [ stateslist(x) | x <- xs ]
> -- stateslist(CompositeState xs) = map stateslist xs
> 
> You see what I'm trying to do?  This is how I want it to behave:
> 
> sm1         = CompositeState [ State 1, State 2, State 3 ]
> stateslist(sm1)
> 	=> [1, 2, 3]

Maybe...

    stateslist :: StateNode a -> [a]
    stateslist (State x) = [x]
    stateslist (CompositeState xs) = concatMap stateslist xs

Greg Buchholz


More information about the Haskell mailing list