如何更新纯函数? [英] How to update pure function?
问题描述
我正在尝试执行以下操作:我想编写一个具有给定功能f
的函数translate(f, c)
(例如,我们知道f
是单个变量x
的函数)和一个常量c
并返回计算f(x+c)
的新函数.
I'm trying to do the following: I want to write a function translate(f, c)
that takes a given function f
(say we know f
is a function of a single variable x
) and a constant c
and returns a new function that computes f(x+c)
.
我知道在Python函数中是一流的对象,我可以将f
作为参数传递,但是我也想不出一种方法,而不必通过x
,这会失败目的.
I know that in Python functions are first-class objects and that I can pass f
as an argument, but I can't think of a way to do this without passing x
too, which kind of defeats the purpose.
推荐答案
诀窍是让翻译返回函数 instance .
The trick is for translate to return a function instance.
def translate(f, c):
def func(x):
return f(x + c)
return func
现在变量x
是免费的",并且名称f
和c
来自封闭的作用域.
Now the variable x
is "free", and the names f
and c
are coming from an enclosing scope.
这篇关于如何更新纯函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!