-1

I found the Python built-in function eval, but failed to find a function that is analogous to Scheme's apply.

I have exhaustively examined other Python keywords, but none of them match apply.

A candidate might be exec:

In [14]: eval("print('testing')")      
testing
In [15]: exec("print('testing')")      
testing

and in Scheme:

> (eval '(display 'testing))
testing
> (apply display '(testing))
testing

Is Python's exec the counterpart to Scheme's apply?

Flux
  • 9,805
  • 5
  • 46
  • 92
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

2 Answers2

2

No. Scheme's apply is used to apply a function to arguments stored in a list. The Python way to do that is *, not exec:

>>> args = [1, 2, 3]
>>> print(*args)
1 2 3

Python used to have an apply function matching Scheme's apply, but it was removed in favor of * notation.

user2357112
  • 260,549
  • 28
  • 431
  • 505
2

To define apply in Python:

def apply(f, arg_list):
    return f(*arg_list)

Scheme example:

(define (pythagoras a b)
  (sqrt (+ (* a a) (* b b))))

(apply pythagoras '(3 4))  ; Returns: 5

Analogous Python example:

import math

def pythagoras(a, b):
    return math.sqrt(a**2 + b**2)

apply(pythagoras, [3, 4])  # Returns: 5.0

Side notes (based on your apparent interest in such things)

Python's eval:

eval('pythagoras(3, 4)')

Whereas in Scheme:

(eval '(pythagoras 3 4))
(eval "Hello")
(eval `(,(if (> x 0) + -) 100 ,(pythagoras 3 4)))

As you can see, Python's eval requires you to fiddle with strings, bytes or "code objects". Scheme's eval takes in Scheme. See: What exactly does homoiconicity mean?

You may be interested in reading about The Metacircular Evaluator (from Structure and Interpretation of Computer Programs, chapter 4, Metalinguistic Abstractions) to see the meaning of Scheme's eval and apply.

Note that the use of eval in Python is heavily discouraged (and if you really need to use it, consider ast.literal_eval instead). In both languages, you are generally advised to avoid eval if your problem can be solved using other methods.

Flux
  • 9,805
  • 5
  • 46
  • 92