Cannot use function call as first argument in s-exp [duplicate]

主宰稳场 提交于 2019-12-01 12:36:24

If answered a similar question already on Stackoverflow. It's a duplicate. Would need to find it.

Anyway.

(defun makefun(x) ;1
  (lambda (z)
    (+ x z)))

((makefun 1) 2)

Common Lisp does not allow evaluation in the function position. It requires you to put a symbol or an actual lambda expression there.

Remember: Common Lisp has a separate function namespace. The value namespace is different. Here MAKEFUN returns a value and this value is not available in the function namespace.

There are only two syntactic ways to call a function:

(foo 1 2)

and

((lambda (a b) (list a b)) 1 2)

See CLHS (Conses as Forms). Here we have a Lambda Form.

Adding the capability to write ((some-function-returning-function) 1 2) would make function calling in Common Lisp more confusing:

  • (foo 1 2) would use the function namespace
  • ((some-function-returning-function) 1 2) would use the value namespace
danlei

Common Lisp has several different namespaces, and in function forms, the functional value of the operator is used. Your lambda example works, because lambda forms are a separate branch in the evaluation rules. You can just google for "Common Lisp namespaces" "Lisp-1 vs. Lisp-2" for more details, and there are quite a few questions and answers here on SO that cover those topics.

But, to answer your particular question, use funcall (you can also take a look at apply):

(funcall (makefun 1) 2)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!