[Haskell-beginners] recursion and pattern matching

Alia alia_khouri at yahoo.com
Tue Oct 18 10:34:14 CEST 2011


I have a question about what's the idiomatic way to walk a tree where there is also a requirement
for pattern-matching to draw variables out of the Node 'container':



<Test.hs>

module Test

where

data Tree a b = EmptyTree | Node a b [Tree a b] 
            deriving (Show, Read, Eq)  
  
t =  Node "goal" 1.0 [
        Node "c1" 0.5 [
            Node "c3" 3.0 [
                Node "c5" 1.0 []
                ]
            ],
        Node "c2" 0.5 [
            Node "c4" 2.0 []
            ]
     ]


sumTree :: (Num b) => Tree a b -> b
sumTree EmptyTree = 0
sumTree (Node _ value []) = value
sumTree (Node _ value [x]) = value + sumTree x
sumTree (Node name value (x:xs)) = value + sumTree x + sumTree (Node name 0 xs)

depth :: Tree a b -> Int
depth EmptyTree = 0
depth (Node _ _ []) = 1
depth (Node _ _ [x]) = 1 + depth x
depth (Node n v (x:xs)) = 1 + depth (Node n v xs) 

</Test.hs>

Interactively:

*Test> sumTree t
8.0
*Test> depth t
4
*Test> 


This seems to work, but I have a sense that one should use folds and fmap and that there
is a better and cleaner what to do this.

Any help would be much appreciated.

Thanks

AK



More information about the Beginners mailing list