How do I compose Linq Expressions? ie Func>, Exp>, Exp>>

前端 未结 2 549
[愿得一人]
[愿得一人] 2020-12-08 16:22

I\'m creating a Validator class. I\'m attempting to implement the Linq SelectMany extension methods for my validator to be able to compose

2条回答
  •  我在风中等你
    2020-12-08 16:48

    The equivalent of Haskell's function composition operator

    (.) :: (b->c) -> (a->b) -> (a->c)
    f . g = \ x -> f (g x)
    

    would in C# probably be something like

    static Expression> Compose(
        Expression> f,
        Expression> g)
    {
        var x = Expression.Parameter(typeof(A));
        return Expression.Lambda>(
            Expression.Invoke(f, Expression.Invoke(g, x)), x);
    }
    

    Is this what you're looking for?

    Example:

    Compose(y => y.ToString(), x => x + 1).Compile()(10); // "11"
    

提交回复
热议问题