How to pass a list a parameter in LISP

Viewed 78

I am currently trying to implement a factorial function for a class. My function takes one argument n, and lists the factorials from 0, 1, 2, ... n.

This is what I currently have:

This is the function I will be calling, right now it just returns the factorial of N:

(defun factor3 (N)
    (apply #'* (loop :for n :from 1 :below (+ 1 N) :collect n))   
)

This is a helper function that returns a list of integers from 1 until num. Acc, when called initially, takes NIL as an empty list to accumulate the values:

(defun my-seq (num acc) 
    (if (eq num 0) 
        acc
        (my-seq (- num 1) (cons num acc)))

Each of these functions act as expected individually, now I want to apply the factor3 function to each member of the list that is returned from my-seq, and my professor has hinted at two keywords:

  • Using apply

  • Using mapcar

However, when I call

(mapcar 'factor3 '(my-seq 5 NIL))

I get

*** - +: MY-SEQ is not a number

So, I try saving the returned list from my-seq to a variable b, then I call

(mapcar 'factor3 'b)

And I get

*** - MAPCAR: A proper list must not end with B

I have tried many different variable names and I get the same error. How should I implement this code?

It seems all I need to do is pass the return as a parameter, but there are such limited resourced on the internet for the LISP language.

Any help is appreciated, thank you.

3 Answers

Don't quote expressions and variables that should be evaluated.

(mapcar 'factor3 (my-seq 5 NIL))

or

(defvar b (my-seq 5 NIL))
(mapcar 'factor3 b)

See the difference between evaluation of a quoted list and just the list:

QUOTED

CL-USER 4 > '(factor3 42)
(FACTOR3 42)

CL-USER 5 > (describe '(factor3 42))

(FACTOR3 42) is a LIST
0      FACTOR3
1      42

NON-QUOTED:

CL-USER 6 > (factor3 42)
1405006117752879898543142606244511569936384000000000

Summary

If you want to compute a value, then you have to leave the form to be evaluated non-quoted.

i think this code is must usefull

(defun factor (n)
   (labels ((built-in-factor (x)
             (if (< x 2)
                 1
                 (* x (built-in-factor (1- x))))))
     (if (numberp n)
         (mapcar #'built-in-factor (loop for i from 1 to n collect i))
         '(oops your value is not number))))
Related