Skip to content

Commit 45a2de4

Browse files
committed
[fix] added missing foldable for trees
1 parent 1874688 commit 45a2de4

File tree

3 files changed

+16
-8
lines changed

3 files changed

+16
-8
lines changed

src/Data/Container/Base/InstanceInterfaces.idr

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import Data.Container.Base.Extension.Instances
1313
import Data.Container.Base.Concrete.Instances
1414

1515
import Data.Tree
16+
import Data.Container.Base.TreeUtils
1617
import Data.Algebra
1718
import Misc
1819

@@ -129,6 +130,11 @@ namespace BinTreeLeafInstances
129130
Num a => Algebra BinTreeLeaf' a where
130131
reduce = reduce {f=BinTreeLeaf} . toBinTreeLeaf
131132

133+
||| Requires making a choice on which subtree to process first
134+
public export
135+
Foldable BinTreeLeaf' where
136+
foldr f z t = foldr {t=BinTreeLeaf} f z (toBinTreeLeaf t)
137+
132138

133139
namespace BinTreeNodeInstances
134140
||| Is there a different way to convince Idris' totality checker?

src/Data/Tree.idr

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -120,17 +120,18 @@ namespace BinaryTrees
120120
pure x = Leaf x
121121
fs <*> xs = map {f=BinTreeLeaf} (uncurry ($)) $ liftA2BinTreeLeaf fs xs
122122

123-
-- Is this even possible?
124-
-- probably is, but foldable really means traversing in a linear order
125-
-- with tree in principle we'd have to process each subtree in parallel
126-
-- but we could implement foldable by first making a choice on how to traverse a tree and turn it into a list, and then performing the fold on the resulting list
123+
||| This requires us traversing a tree in a linear order
124+
||| This means we have to make a choice on which subtree to process first
125+
||| Another way is to first implement a traversal of the tree, and
126+
||| then use that
127127
public export
128128
Foldable BinTreeLeaf where
129129
foldr f z (Leaf leaf) = f leaf z
130-
foldr f z (Node _ leftTree rightTree) = ?oo_1 where
131-
leftTreeRes : acc
132-
leftTreeRes = foldr {t=BinTreeLeaf} f z leftTree
133-
rightTreeRes = foldr {t=BinTreeLeaf} f z rightTree
130+
foldr f z (Node () leftTree rightTree) =
131+
-- Process left first, i.e. fold right with z, then use that
132+
-- as accumulator for left
133+
let rightResult = foldr {t=BinTreeLeaf} f z rightTree
134+
in foldr {t=BinTreeLeaf} f rightResult leftTree
134135

135136
namespace NodesOnly
136137
public export

tensortype.ipkg

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ modules = Data.Container.Base
4444
, Data.Container.Applicative.Extension.Instances
4545
, Data.Container.Applicative.Concrete.Instances
4646
, Data.Container.Applicative.Product.Interfaces
47+
, Data.Container.Applicative.TreeUtils
4748

4849
, Data.Container.SubTerm
4950

0 commit comments

Comments
 (0)