Quick implementation of the Haskell binary tree

I implemented a binary tree data structure in Haskell.

My code is:

module Data.BTree where

data Tree a = EmptyTree 
                | Node a (Tree a) (Tree a)
                deriving (Eq, Ord, Read, Show)

emptyTree :: a -> Tree a  
emptyTree a = Node a EmptyTree EmptyTree

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = emptyTree x
treeInsert x  (Node a left right) 
        | x == a = (Node x left right)
        | x < a =  (Node a (treeInsert x left) right)   
        | x > a =  (Node a left (treeInsert x right))


fillTree :: Int -> Tree Int -> Tree Int
fillTree  10000 tree = tree 
fillTree  x tree = let a = treeInsert x tree
                   in fillTree (x + 1) a

This code is very slow. I launched:

fillTree 1 EmptyTree

I get: 50.24 sec

I am trying to implement this code in C and my result of this test is: 0m0.438s

Why is there such a big difference? Is the Haskell code too slow, or is my binary tree in haskell bad? I want to ask a gutsuka guru, maybe I can make the binary tree implementation more efficient?

Thank.

+5
source share
2 answers

, C. . , O (n ^ 2) Haskell O (n) C. Nevermind, , , O (n ^ 2) . , .

, , ghci. "" "ghci" "". , , . . , - , 50 .

+6

-, : Set Data.Set . fillTree, , :

import qualified Data.Set as Set
import Data.Set (Set)

fillSet :: Int -> Set Int -> Set Int
fillSet 10000 set = set
fillSet x set = let a = Set.insert x set
                in fillSet (x + 1) a

fillSet 1 Set.empty GHCi, , , , . , , -, , .

, Data.Set.Set , , . - .. - . Data.Set.Set , .

Set:

data Set a = Tip 
           | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)

, , , .

Data.Set ; .


, . :

toList EmptyTree = []
toList (Node x l r) = toList l ++ [x] ++ toList r

main = print . sum . toList $ fillTree 1 EmptyTree

, , , . , , , , , . :

  • runhaskell, GHCi:

    real    1m36.055s
    user    0m0.093s
    sys     0m0.062s
    
  • ghc --make -O0:

    real    0m3.904s
    user    0m0.030s
    sys     0m0.031s
    
  • ghc --make -O2:

    real    0m1.765s
    user    0m0.015s
    sys     0m0.030s
    

Data.Set :

  • runhaskell:

    real    0m0.521s
    user    0m0.031s
    sys     0m0.015s
    
  • ghc --make -O2:

    real    0m0.183s
    user    0m0.015s
    sys     0m0.031s
    

: GHCi - .

+14

All Articles