Function that returns first element of a list

Asked

Viewed 87 times

0

I am trying to make a function that will return the first element of a list in Clisp.

I have the following code:

(defun pr(NomeDaCidade X Y)
    (first '(NomeDaCidade X Y)))

And trying to call it like that:

(pr '('Lisboa' 3 4))

The Clisp blows up. I can’t identify my mistake.

1 answer

0


Makes much time I don’t deal with Lisp, but from what little I remember:

(defun pr(NomeDaCidade X Y)

Here you define a function that takes 3 parameters (not a list). Therefore, to get only the first element, you wouldn’t even need to create a list and call first, just do:

(defun pr(NomeDaCidade X Y)
    NomeDaCidade)

(pr "Lisboa" 3 4) ; chama a função com 3 parâmetros

Note that when calling the function, we pass the 3 parameters separately instead of passing a list with them. But that’s a pretty useless function, since she ignores the other 2 parameters (unless, of course, she uses X and Y for other things, before returning the name of the city).


If the idea is to receive a list, then the function should only have one parameter, which is the list. Then you only return the first element of it:

(defun pr(lista)
    (first lista))

(pr '("Lisboa" 3 4)) ; chamar função passando uma lista com os valores

Now yes I call the function by passing a list, and inside it I get only the first element.


Of course, the above function is still kind of useless, because I’m ignoring the other elements. But you could pick them up like this:

(defun pr(lista)
    ; obtém os elementos da lista e coloca-os em variáveis
    (setq nomeCidade (first lista)
          x (nth 1 lista)
          y (nth 2 lista))

    ; supondo que a função faz outras coisas com x e y ...

    nomeCidade) ; retorna o primeiro elemento

(pr '("Lisboa" 3 4)) ; passar uma lista com os valores

Browser other questions tagged

You are not signed in. Login or sign up in order to post.