haskell - Defining fmap for a binary search tree -


i'm working through exercises in book "beginning haskell." exercise 4-8 make binary search tree instance of functor , define fmap. tree looks like:

data binarytree = node (binarytree a) (binarytree a)                    | leaf                     deriving show 

because search tree, operations on tree must maintain invariant values in left subtree < node's value , values in right subtree > node's value. means values in tree must ordinal (ord => binarytree a).

two questions:

  1. since fmap :: (a -> b) -> binarytree -> binarytree b, how enforce b ordinal? if didn't have functor, fmapord :: (ord a, ord b) => (a -> b) -> binarytree -> binarytree b, functor typeclass doesn't enforce ord contraints.
  2. what efficient implementation like? first thought fold on tree, , build new tree out of mapped values. unfortunately, didn't far because of (1).

the point of functors , fmap works a , b can stored in data structure, monad has work types a well. functor instance should like

instance functor binarytree     fmap f leaf = leaf     fmap f (node l r) = node (f a) (fmap f l) (fmap f r) 

but if want ensure mapping on binary tree keeps balanced, need function

balancetree :: ord => binarytree -> binarytree 

you should able implement function googling, can define specialized mapping function

binmap :: (ord a, ord b) => (a -> b) -> binarytree -> binarytree b binmap f = balancetree . fmap f 

and should ensure , users of library never use fmap (unless necessary) , instead use binmap.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -