eta*_*let 5 ruby python function
在学习Python之后我正在努力学习Ruby,而我在将这段代码翻译成Ruby时遇到了麻烦:
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
Run Code Online (Sandbox Code Playgroud)
我是否必须使用块翻译?或者Ruby中有类似的语法?
你可以用Ruby中的lambdas(我在这里使用1.9 stabby-lambda)来做到这一点:
compose = ->(f,g) {
->(x){ f.(g.(x)) }
}
Run Code Online (Sandbox Code Playgroud)
这compose是一个返回另一个函数的函数,如下例所示:
f = ->(x) { x + 1 }
g = ->(x) { x * 3 }
h = compose.(f,g)
h.(5) #=> 16
Run Code Online (Sandbox Code Playgroud)
请注意,函数式编程并不是Ruby的强项 - 它可以完成,但在我看来它看起来有些混乱.
可以说f和g是以下方法:
def f(x)
x + 2
end
def g(x)
x + 3
end
Run Code Online (Sandbox Code Playgroud)
我们可以定义compose1为:
def compose1(f,g)
lambda { |x| send(f, send(g, x) ) }
end
Run Code Online (Sandbox Code Playgroud)
为此,我们需要将 h 定义为:
h = compose1(:f, :g)
您需要将方法名称作为字符串/符号传递才能send工作。然后,你可以做
h.call 3 # => 8。更多信息可以在这里找到