目录
终端语言(如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
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
4 // #^2 & // #*2 & // Print
c#
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++
#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
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
}
标签:square,return,编程语言,int,double,pipe,result,链式
From: https://www.cnblogs.com/yhm138/p/17376006.html