复合函数的意思就是:
有函数:
f(x)=x + 1;
g(x)=x * x
则g(f(x)) = (x + 1) * (x + 1)
我们给Ruby的打开Proc类:
有函数:
f(x)=x + 1;
g(x)=x * x
则g(f(x)) = (x + 1) * (x + 1)
我们给Ruby的打开Proc类:
class Proc
def self.compose(f, g)
lambda { |*args| f[g[*args]] }
end
def *(g)
Proc.compose(self, g)
end
end
inc = lambda { |x| x + 1 }
square = lambda{ |x| x * x}
square_inc = square * inc
square_inc(2) #=> 9
本文介绍了复合函数的概念,并通过Ruby语言展示了如何实现函数的组合。使用Proc类定义了compose方法来实现函数组合,并通过示例代码展示其用法。
5860

被折叠的 条评论
为什么被折叠?



