[Haskell-beginners] Data.Tree computation

Gabi bugspynet at gmail.com
Fri Feb 12 04:31:49 EST 2010


Hi guys,
I've tried to use Data.Tree as a computation tree (each node is
numerical function, each leaf is a terminal)
It kinda works, but the code seems very verbose.  How can it made more
concise ? I am sure I missed a lot of shortcuts and idioms.

-- file t.hs
import qualified Data.Tree as T

data Term = TInt Int| TDouble Double
            deriving (Show, Eq)

data Func = Plus | Minus | Mult | Div
            deriving (Show, Eq)

data ANode = GFunc Func | GTerm Term
              deriving (Show, Eq)

fNode :: Func -> T.Forest ANode-> T.Tree ANode
fNode f = T.Node (GFunc f)

tNode:: Term -> T.Tree ANode
tNode t = T.Node (GTerm t) []

calc :: T.Tree ANode -> Double
calc (T.Node (GTerm (TInt n))[]) = fromIntegral n :: Double
calc (T.Node (GFunc Plus) xs ) = foldl1 (+) (map calc xs)
calc (T.Node (GFunc Minus) xs ) = foldl1 (-) (map calc xs)
calc (T.Node (GFunc Mult) xs ) = foldl1 (*) (map calc xs)
calc (T.Node (GFunc Div) xs ) = foldl1 (/) (map calc xs)

-- (/ (+ 5 5 (- 10 100)) 10) -  calc Should return -8.0
aTree =  fNode Div [fNode Plus [tNode $ TInt 5,tNode $ TInt 5, fNode
Minus [tNode $ TInt 10,tNode $ TInt 100]], tNode (TInt 10)]


Regards,
Gabi

http://bugspy.net


More information about the Beginners mailing list