Sample usage Structure.Collect in C#?

(exbrain) #1

What does it do Structure.Collect ? I tried to use it
Could you show example C# ?



Not sure why you want to use this function, but you can do it as follows:

        var chooser =
         FSharpFunc<Expression, FSharpOption<Expression>>
            x =>
                if (x is Number)
                    return FSharpOption<Expression>.Some(x);
                return FSharpOption<Expression>.None;

        var values = Structure.Collect<Expression>(chooser, expr);

chooser - your function for selection


another option:

        Converter<Expression, FSharpOption<Expression>> conv =
              (x) =>
                  if (x is Number)
                      return FSharpOption<Expression>.Some(x);
                  return FSharpOption<Expression>.None;


        var values = Structure.Collect<Expression>(conv, expr);

(exbrain) #5

i want to collect sum, product, power in expression tree, this example collect just first-depth expression


Can you show an example expression and that you want to get?

(Tyetis) #7

x^2 + x*(a^6 + b)

get “power” items
x^2 and a^6

get “sum” items
x^2 + x*(a^6 + b) and a^6 + b

i use CollectIdentifiers for filter “x”, “a”, “b”

(Christoph Rüegg) #8

collect does not collect just first-depth expressions only. But it does not continue down a specific sub expression if you return Some on the parent. If you do return Some on the root node, then the root node will be the only one presented to the lambda.

I do see that there are use cases where you want to look at all sub expressions, even if a parent expression has already returned something. I’ll add another function for that.

(Christoph Rüegg) #9

I’ve added a couple new functions to the Structure module:

  • collectAll: like collect, but continues even if the lambda returns Some. So this could be used e.g. to collect also powers within powers.
  • collectSums, collectProducts, collectPowers: collect all sum, product or power terms, recursively (inlcuding e.g. powers within powers)
  • collectPredicate, collectAllPredicate: like collect and collectAll, but accept just a predicate lambda that returns either true or false, instead of an F# option. This should simplify the common cases, especially when used in C#.

(Christoph Rüegg) #10

With v0.13:

var expression = Infix.ParseOrThrow("x^2 + x*(a^6 + b)");

// 2, 6
var allNumbersEx = Structure.CollectAllPredicate(
    (Converter<Expression, bool>)(t => t is Expression.Number),

// 2, 6
var allNumbers = Structure.CollectNumbers(expression);

// a^6 + b, (a^6 + b)*x + x^2
var allSums = Structure.CollectSums(expression);

// a^6, x^2
var allPowers = Structure.CollectPowers(expression);

(Tyetis) #11

I tried the new version. looks nice added functions thanks
actually i using sympy library on python. that’s very handy and I’m trying to do similar to this in dotNet