Cláudio Ribeiro
Cláudio Ribeiro

Reputation: 1699

Lisp - function that returns a function

I want to create a function that receives 2 arguments and returns a function that receives himself a board. That function needs to check user input and make changes in the board according to the input. I have no problems with the user input and the changes i have to do to the board. My problem is with the function that returns a function. To do that i'm using a lambda. This is the code i'm working on:

(defun faz-jogador-manual (n_aneis peca)
#'(lambda (tabuleiro)
    (setf jogada (le-posicao))
    (let ((num_anel (first jogada))
        (posicao_anel (second jogada))
        (tab (copia-tabuleiro tabuleiro)))
    (tabuleiro-poe-peca tab peca num_anel posicao_anel))))

This function should return a function lambda, but when i call the function using:

(faz-jogador-manual 3 'X)

i get the following:

#<Closure (:INTERNAL FAZ-JOGADOR-MANUAL 0) [X] @ #x2112f462>

I don't know what i'm doing wrong, is it the call? is the function per se? I need help with this one.

Upvotes: 1

Views: 1194

Answers (2)

naryl
naryl

Reputation: 151

Closure object is a lambda with lexical variables captured from the context (n_aneis and peca in your case). It's a value you can put into a variable or apply as a function with funcall.

(defvar closure (faz-jogador-manual 3 'X))
(funcall closure *table*)

Upvotes: 2

mqp
mqp

Reputation: 71937

Common Lisp is a Lisp-2, which means that it has a separate namespace for functions and values; as a result, functions need to be treated slightly specially in this case. (This is in contrast to most Lisps.)

When you return a function as a value, you can't just invoke it in the same way as if you had defined it with defun. You need to use funcall or apply to do so. You can do it like this:

;; insert an appropriate argument in place of tabuleiro for the inner function
(funcall (faz-jogador-manual 3 'X) tabuleiro)

If you want to understand this behavior in more detail, you can probably find lots of references online, like this one.

Upvotes: 3

Related Questions