Reputation: 113
Let's say we have the following code representing binary trees where decodeInt
searches the tree for an integer:
import Text.Show.Functions
data BinTree a b = Leaf b | Node a (BinTree a b) (BinTree a b) deriving Show
example :: BinTree (Int -> Bool) Char
example = Node (\x -> x > 4) (Node (\x -> x * x == x) (Leaf 'g') (Node (\x -> x == 0)
(Leaf 'u') (Leaf 'l'))) (Node (\x -> x >= 7) (Leaf 'f') (Leaf 'i'))
countInnerNodes :: BinTree a b -> Int
countInnerNodes (Node a b c) = 1 + countInnerNodes b + countInnerNodes c
countInnerNodes (Leaf x) = 0
decodeInt :: BinTree (Int -> Bool) b -> Int -> b
decodeInt (Leaf b) p = b
decodeInt (Node x y z) p = if (x(p) == True) then decodeInt z p else decodeInt y p
decode :: BinTree (Int -> Bool) b -> [Int] -> String
decode x [] = "empty list"
decode x xs = ??????
How can I use map to get a result like this when calling decode?
decode Tree [1,2,3,4]
= [decodeInt Tree (1), decodeInt Tree (2),
decodeInt Tree (3), decodeInt Tree (4)]
/edit: Followup Let's also say we would like to create a function like the following
mapTree (\x -> ’e’) example
mapTree should return a BinTree just like example with the only difference being that the Char of every Leaf has been replaced with an 'e'. How do I accomplish that? I've started Haskell yesterday so I'm quite new to functional programming.
Upvotes: 1
Views: 364
Reputation: 21
A bit too late but maybe this helps :
decode :: BinTree (Int -> Bool) b -> [Int] -> [b]
decode _ [] = []
decode x (y:ys) = decodeInt x y .... maybe you have an idea how to continue here ;)
Upvotes: 2
Reputation: 532153
decodeInt :: BinTree (Int -> Bool) b -> Int -> b
, so assuming t :: BinTree (Int -> Bool) b
, then decodeInt t :: Int -> b
. You map that function over your list of Int
s.
decode t xs = let y = map (decodeInt t) xs
in ...
You'll still have to figure out how to convert y
to the String
value that decode
is expected to return.
Upvotes: 2