不同的编程语言中使用管道pipe(或者说链式调用)

发布时间 2023-05-06 09:59:41作者: yhm138

终端语言(如bash,zsh)一般有管道符|

# 将 `echo` 命令的输出传递给 `grep` 命令
echo "Hello, World!" | grep "World"

# 将 `ls` 命令的输出传递给 `wc` 命令,以统计文件和目录的数量
ls | wc -l

python

!pip install toolz
from toolz import pipe

def square(x):
    return x * x

def double(x):
    return x * 2

result = pipe(4, square, double)
print(result)  # Output: 32

javascript

!npm install lodash
const _ = require('lodash');

function square(x) {
  return x * x;
}

function double(x) {
  return x * 2;
}

const pipe = _.flow(square, double);

console.log(pipe(4));  // Output: 32

ruby

TIO

def square(x)
  x * x
end

def double(x)
  x * 2
end

module Pipe
  refine Object do
    def pipe(func)
      func.call(self)
    end
  end
end

using Pipe

result = 4.pipe(method(:square)).pipe(method(:double))
puts result  # Output: 32

mathematica

TIO

4 // #^2 & // #*2 & // Print

c#

TIO

using System;

public static class FunctionalExtensions
{
    public static TResult Pipe<T, TResult>(this T input, Func<T, TResult> func) => func(input);
}

public class Program
{
    static int Square(int x) => x * x;
    static int Double(int x) => x * 2;

    public static void Main(string[] args)
    {
        int result = 4.Pipe(Square).Pipe(Double);
        Console.WriteLine(result); // Output: 32
    }
}

c++

TIO

#include <iostream>
#include <functional>
#include <type_traits>

template<typename T>
class Pipeline {
public:
    Pipeline(T value) : value_(value) {}

    template<typename Func>
    auto then(Func&& func) const -> Pipeline<decltype(func(std::declval<T>()))> {
        using ReturnType = decltype(func(std::declval<T>()));
        return Pipeline<ReturnType>(func(value_));
    }

    T get() const { return value_; }

private:
    T value_;
};

int square(int x) { return x * x; }
int doubleVal(int x) { return x * 2; }
std::string to_string(int x) { return std::to_string(x); }

int main() {
    std::string result = Pipeline<int>(4).then(square).then(doubleVal).then(to_string).get();
    std::cout << result << std::endl; // Output: "32"
}

scala 3

ATO

import scala.util.chaining._
object Main extends App{
def square(x: Int): Int = x * x
def double(x: Int): Int = x * 2
val result = 4.pipe(square).pipe(double)
println(result) // Output: 32
}