【问题标题】:Evaluation allows for combinations whose operators are compound expressions评估允许其运算符是复合表达式的组合
【发布时间】:2019-12-24 07:34:01
【问题描述】:

我在sicp中发现了scheme的惊人力量

练习 1.4。观察我们的评估模型允许 运算符为复合表达式的组合。用这个 观察来描述以下过程的行为:

 #+BEGIN_SRC scheme
(define (a-plus-abs-b a b)
  ((if (> b 0) + -) a b))
(a-plus-abs-b 9 4)
 #+END_SRC

 #+RESULTS:
 : 13

我试图模仿它,但不知道如何处理符号运算符

In [13]: 1 eval("+") 1                 
  File "<ipython-input-13-74042a5242a6>", line 1
    1 eval("+") 1
         ^
SyntaxError: invalid syntax


In [14]: 1 exec("+") 1                 
  File "<ipython-input-14-deabdb544acb>", line 1
    1 exec("+") 1
         ^
SyntaxError: invalid syntax

有没有办法像方案一样直接使用符号运算符“+”?

【问题讨论】:

    标签: python python-3.x scheme lisp sicp


    【解决方案1】:

    在 Python 中,我们不能直接传递 +-,我们需要将它们包装在函数中,因为它们是 operators 而不是 procedures Scheme,因此解释器需要区别对待。

    但是,我们可以将 Scheme 代码非常简单地转换为 Python,只需从 operator 模块中导入正确的运算符,然后像任何普通函数一样调用它们:

    from operator import add, sub
    
    def a_plus_abs_b(a, b):
        return (add if b > 0 else sub)(a, b)
    
    a_plus_abs_b(9, 4)
    => 13
    

    operator 模块“导出一组与 Python 的内在运算符相对应的高效函数”。另一种(效率较低的)替代方法是使用lambda

    my_add = lambda x, y: x + y
    my_sub = lambda x, y: x - y
    
    def a_plus_abs_b(a, b):
        return (my_add if b > 0 else my_sub)(a, b)
    
    a_plus_abs_b(9, 4)
    => 13
    

    【讨论】:

      猜你喜欢
      • 2012-05-28
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多