3

I'm trying to write a function such that P(x) for any integer x there is a list of three elements, namely the square, cube, and fourth power of n but I'm stuck on how i can combine then to make one function for example i have the square, cube and the power 4 function here are my functions below

(defun p(x) (* x x))

(defun p(x) (* x x x))

(defun p(x) (expt x x) //thought i am not sure about this one

is there a way i can make my result(i.e function p(x) ) list look like (4 27 256) if I have a list of ( 2 3 4) after executing the program? Was thinking of mapcar function though I'm not sure on how I can go about it. Any suggestions?

2
  • 1
    if you want to create a list, how about the function LIST? Commented Oct 8, 2012 at 18:49
  • i thought about it but im just a newbie dont know how to manipulate the functions Commented Oct 8, 2012 at 19:07

3 Answers 3

4

Yes, mapcar could be a way to go.

;; a simple solution.
(defun expt-list (n powers)
  (mapcar #'(lambda (x) (expt n x)) powers))

;; a bit more complex, so you  don't compute powers of the same 
;; base multiple times.
(defun expt-list-memoize (n powers)
  (let ((hash (make-hash-table)))
    (mapcar #'(lambda (x)
                (let ((y (gethash x hash)))
                  (if y y (setf (gethash x hash) (expt n x)))))
            powers)))
Sign up to request clarification or add additional context in comments.

2 Comments

how do i enter the numbers or arguments its giving some error i do not know why
im getting expt-list at the end but when i enter (expt-list 2 3 5) its not working,am i missing something?
1

There is one oddity in Common Lisp, that one has to recognize: If you want to refer to a function via a symbol, you will have to quote it with (function p) or with the abbrevation #'p

Given

(defun p(x) (* x x))

you can compute a list of squares with

CL-USER> (mapcar #'p (list 1 2 3 4))

(1 4 9 16)

Comments

0

The requirements here are a little fuzzy but if the intent is, given a call such as (expt-list 2 3 4) to have returned a list of each number raised to its own power, eg:

(expt-list 2 3 4)
=> (4 27 256)

would something along the lines of:

(defun expt-list (&rest list-of-n)
  "return a list of each 'n' in LIST-OF-N raised to its own power"
  (loop for n in list-of-n collect (expt n n)))

do the trick?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.