Skip to content

Commit

Permalink
LeafCount
Browse files Browse the repository at this point in the history
  • Loading branch information
corywalker committed Aug 29, 2017
1 parent 33368cc commit ae4be07
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
20 changes: 20 additions & 0 deletions expreduce/builtin_expression.go
Expand Up @@ -29,6 +29,17 @@ func flattenExpr(src *Expression, dst *Expression, level int64, cl *CASLogger) {
}
}

func leafCount(e Ex) int64 {
if asExpr, isExpr := e.(*Expression); isExpr {
res := int64(0)
for _, part := range asExpr.Parts {
res += leafCount(part)
}
return res
}
return 1
}

func GetExpressionDefinitions() (defs []Definition) {
defs = append(defs, Definition{
Name: "Head",
Expand Down Expand Up @@ -131,6 +142,15 @@ func GetExpressionDefinitions() (defs []Definition) {
return dst
},
})
defs = append(defs, Definition{
Name: "LeafCount",
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
if len(this.Parts) != 2 {
return this
}
return NewInt(leafCount(this.Parts[1]))
},
})
defs = append(defs, Definition{
Name: "Flat",
OmitDocumentation: true,
Expand Down
4 changes: 2 additions & 2 deletions expreduce/resources.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions expreduce/resources/expression.m
Expand Up @@ -126,3 +126,13 @@
ESameTest[{-1, 1[{{1}, 2}], 3, 4}, Flatten[{-1, {1[{{1}, 2}]}, 3, 4}, 999]]
]
};

LeafCount::usage = "`LeafCount[e]` returns the count of leaves in `e`.";
Attributes[LeafCount] = {Protected};
Tests`LeafCount = {
ESimpleExamples[
ESameTest[3, LeafCount[a+b]],
ESameTest[8, LeafCount[a^2 + b^(c!)]],
ESameTest[1, LeafCount[a]]
]
};

0 comments on commit ae4be07

Please sign in to comment.