[Haskell-cafe] bit of help with n-ary please...

Daniel Fischer daniel.is.fischer at web.de
Sun Nov 8 19:12:40 EST 2009


Am Sonntag 08 November 2009 23:24:59 schrieb spot135:
> Hi,
>
> Ok what im trying to do is replace an element in an n-ary and display the
> completed tree.
>
> So this is what ive got so far.
>
> data Tree a = Empty |Leaf a|Branch a [Tree a]
> 				deriving (Show)
>

replace x y tree

should give a tree with the same structure, values equal to x should be replaced by y, all 
other values left as they are?

>
> replace :: Eq a=>a->a->Tree a -> (Tree a)
>
> replace x y Empty = Element x

That should surely be

replace _ _ Empty = Empty ?

>
> replace x y (Leaf z)
>
> 	| x==z = (Leaf y)
>
> --	| otherwise =

    | otherwise = Leaf z


>
> replace x y (Branch z lis)
>
> 	| x==z = (Branch y lis)
> 	|otherwise = replaceA x y clis

You'd want to recur, I believe, use

map (replace x y)

>
> replaceA :: Eq a=> a->a->[Tree a]->(Tree a)
> replaceA _ _ [] = Empty -- run out
> replaceA x y (h:r)
>
> 	|Q suc = suc
> 	|otherwise = replaceA x y r
>
> 	where suc=replace x y h
>
> Q :: a -> Bool
> Q a = True
> Q a = False
>
> Theres two main problems i am having. One is I'm not sure what should be
> the "otherwise" in the leaf function. Another problem is it doesn't show
> the whole tree just the part after the replacement.
>
> If you think this is complete bull I'll quite happily start over if
> somebody could give me some insight
> into what is the best way of tackling this problem is.
>
> Many thanks in advance
>
> spot



More information about the Haskell-Cafe mailing list