Pipe forwards in C#

前端 未结 4 1296
醉酒成梦
醉酒成梦 2020-12-02 14:51

Continuing my investigation of expressing F# ideas in C#, I wanted a pipe forward operator. For anything wrapped in a IEnumerable, we already have it, as you can .NextFunc()

4条回答
  •  醉酒成梦
    2020-12-02 15:22

    So for Piping I don't think there is expectation to check for null and not call the piped function. The function argument in many cases could easy take a null and have it handled by the function.

    Here is my implementation. I have Pipe and PipeR. Be forewarned, the PipeR is not pipe right, but just for the cases in which the target is in the opposite position for currying, because the alternate overloads allow limited fake currying of parameters.

    The nice thing about the fake currying is that you can pipe in the method name after providing the parameters, thus producing less nesting than you would with a lambda.

    new [] { "Joe", "Jane", "Janet" }.Pipe(", ", String.Join)
    

    String.Join has the IEnumerable in the last position so this works.

    "One car red car blue Car".PipeR(@"(\w+)\s+(car)",RegexOptions.IgnoreCase, Regex.IsMatch)
    

    Regex.IsMatch has the target in the first Position so PipeR works.

    Here's my example implementaion:

    public static TR Pipe(this T target, Func func)
    {
        return func(target);
    }
    
    public static TR Pipe(this T target, T1 arg1, Func func)
    {
        return func(arg1, target);
    }
    
    public static TR Pipe(this T target, T1 arg1, T2 arg2, Func func)
    {
        return func(arg1, arg2, target);
    }
    
    public static TR PipeR(this T target, T1 arg1, Func func)
    {
        return func(target, arg1);
    }
    
    public static TR PipeR(this T target, T1 arg1, T2 arg2, Func func)
    {
        return func(target, arg1, arg2);
    }
    

提交回复
热议问题