V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
amlee
V2EX  ›  Python

本来以为生成器了解的差不多了,结果这段代码把我看懵了

  •  
  •   amlee · 2022-11-09 05:24:40 +08:00 · 4602 次点击
    这是一个创建于 505 天前的主题,其中的信息可能已经有所发展或是发生改变。
    12 条回复    2022-11-09 19:43:25 +08:00
    dangyuluo
        1
    dangyuluo  
       2022-11-09 06:10:55 +08:00
    一句话里好多语法时态错误😓
    amlee
        2
    amlee  
    OP
       2022-11-09 06:15:25 +08:00
    @dangyuluo 不好意思,doctest 是我手敲的,抄错了,现在改了
    dingwen07
        3
    dingwen07  
       2022-11-09 06:31:31 +08:00   ❤️ 1
    因为一两句话说不清楚的原因,如果不用递归就得这么写:
    def apply_many(f):
    agg = f
    while True:
    yield agg
    new = lambda agg=agg: lambda x: f(agg(x))
    agg = new()
    geelaw
        4
    geelaw  
       2022-11-09 07:45:42 +08:00
    这个其实很好理解,就是:

    apply_many(x) = x + x^2 + x^3 + x^4 + ... = x + x (x + x^2 + x^3 + ...) = x + x apply_many(x)

    如果你把 + 理解为列表拼接并把 * 理解为函数复合
    hbdh5
        5
    hbdh5  
       2022-11-09 09:21:33 +08:00
    haskell 可以更简洁

    apply_many f = iterate nxt f
    where nxt f = f . f
    hbdh5
        6
    hbdh5  
       2022-11-09 09:30:08 +08:00
    或者 apply_many f = iterate (. f) f
    CzaOrz
        7
    CzaOrz  
       2022-11-09 09:37:20 +08:00
    一般程序员看递归都会有点困惑,像我这种有点经验的,看了也是一脸懵逼 [旺柴]
    Alias4ck
        8
    Alias4ck  
       2022-11-09 09:46:15 +08:00   ❤️ 1
    这个还好吧 我之前看一段 high order 的代码实现 kv store 才叫有趣 https://gist.github.com/noahlias/083195d728fc722d663c7432cbd612cc
    shuizhongyu10
        9
    shuizhongyu10  
       2022-11-09 10:14:57 +08:00
    @Alias4ck 有意思哦 问下除了涨见识外 这种代码有什么实际的应用吗?
    lookStupiToForce
        10
    lookStupiToForce  
       2022-11-09 11:14:04 +08:00
    提个问题,有大佬帮忙解答吗?
    如果不按 next(gen) 去调用,是否会造成无限递归或者内存泄漏?
    lookStupiToForce
        11
    lookStupiToForce  
       2022-11-09 11:58:23 +08:00
    另外 op 的递归生成函数的函数,怎么改才能使它支持使用任意数量参数的函数(这个函数使用多少个变量就能返回多少个变量)啊?😂
    amlee
        12
    amlee  
    OP
       2022-11-09 19:43:25 +08:00   ❤️ 1
    @lookStupiToForce 我不知道你指的是不是 apply_many 中传入的 f 具有多个参数?

    如果是的话,可以考虑不要改 apply_many ,而是使用柯里化处理 f ,生成一个新的单一参数的函数,再给 apply_many 处理。

    另外,不用柯里化的话,python 自带的 partial 也能做到跟柯里化差不多的效果。https://docs.python.org/zh-cn/3/library/functools.html#functools.partial
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5483 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 08:21 · PVG 16:21 · LAX 01:21 · JFK 04:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.