I am new to Purescript so I was trying to implement fold left and fold right (aka reduce) for my custom Tree data structure, but I am having problem implementing logic for fold right:
data Tree a = Leaf a | Node (Tree a) (Tree a)
instance foldableTree :: Foldable Tree where
foldl f d (Node left right) = foldl f (foldl f d left) right
foldl f d (Leaf a) = f (d) (a)
foldr f d (Node left right) = ???
foldr f d (Leaf a) = ???
I only got so far with implementation:
instance foldableTree :: Foldable Tree where
foldl f d (Node left right) = foldl f (foldl f d left) right
foldl f d (Leaf a) = f (d) (a)
foldr f d (Node left right) = f (foldr f d left) (foldr f d right)
foldr f d (Leaf a) = a
But this implementation is flawed because deafult value is not passed to the fold
I solved it, I only needed to use same logic as on fold left but with swapped arguments for Leaf and for the recursive function "foldr" by first providing right side then left side:
instance foldableTree :: Foldable Tree where
foldl f d (Node left right) = foldl f (foldl f d left) right
foldl f d (Leaf a) = f d a
foldr f d (Node left right) = foldr f (foldr f d right) left
foldr f d (Leaf a) = f a d
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.