haskell - Recursively adding to binary tree -


i'm trying recursively add binary tree in haskell. i'm following learn haskell on this, few changes, i'm getting errors, not understand:

data male = male { malename :: string                  , maledob :: int                  } deriving (show, read, eq, ord)  data female = female { femalename :: string                      , femaledob :: int                      } deriving (show, read, eq, ord)  data familytree = emptytree                    | node (familytree female) (familytree male)                   deriving (show, read, eq, ord)  singleton :: -> familytree singleton x = node x emptytree emptytree  treeinsert :: (ord a) => -> familytree -> familytree treeinsert x emptytree = singleton x treeinsert x (node left right)     | x == = node x left right     | x <  = node (treeinsert x left) right     | x >  = node left (treeinsert x right) 

here error message i'm getting:

couldn't match type `female' `male' expected type: male   actual type: in first argument of `treeinsert', namely `x' in third argument of `node', namely `(treeinsert x right)' in expression: node left (treeinsert x right) 

i'm quite new haskell , can't wrap head around happening here. pointer in right direction welcome!

when write

treeinsert :: ord => -> familytree -> familytree 

the type system ensures type of first argument equals index of second. means can insert male in tree starts male. guess, not want.

however it's nice question , i'll answer it. problem in

treeinsert :: ord => -> familytree -> familytree 

is a far general. would

treeinsert :: int -> familytree int -> familytree int 

mean? need restrict a either female or male. that's job gadts:

{-# language gadts #-}  data person     pfemale :: female -> person female     pmale   :: male   -> person male 

person contains either female or male , carries @ type level information one. having can define

runperson :: person -> runperson (pfemale x) = x runperson (pmale   x) = x  treeinsert :: person -> familytree -> familytree treeinsert p              emptytree          = singleton (runperson p) treeinsert p@(pfemale x) (node left right)     | x ==    = node x left right     | otherwise = treeinsert p left treeinsert p@(pmale   x) (node left right)     | x ==    = node x left right     | otherwise = treeinsert p right 

the trick when pattern match on person a a gets instantiated either female or male , never else. when a female, continue insert "female" subtree, otherwise — "male".


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -