如何更新纯函数? [英] How to update pure function?

查看:63
本文介绍了如何更新纯函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作:我想编写一个具有给定功能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是免费的",并且名称fc来自封闭的作用域.

Now the variable x is "free", and the names f and c are coming from an enclosing scope.

这篇关于如何更新纯函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆