评估允许运算符为复合表达式的组合
Evaluation allows for combinations whose operators are compound expressions
我在sicp
中发现了方案的惊人力量
Exercise 1.4. Observe that our model of evaluation allows for
combinations whose operators are compound expressions. Use this
observation to describe the behavior of the following procedure:
#+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中我们不能直接传递+
或-
,我们需要将它们包装在函数中,因为它们是运算符 而不是 Scheme 中的 procedures,因此需要由解释器区别对待。
但是,我们可以将 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
模块 "exports a set of efficient functions corresponding to the intrinsic operators of 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
我在sicp
中发现了方案的惊人力量Exercise 1.4. Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:
#+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中我们不能直接传递+
或-
,我们需要将它们包装在函数中,因为它们是运算符 而不是 Scheme 中的 procedures,因此需要由解释器区别对待。
但是,我们可以将 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
模块 "exports a set of efficient functions corresponding to the intrinsic operators of 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