Reputation: 1
This is my first program in LISP. The language we are using is TinyLISP ( http://www.ugcs.caltech.edu/~rona/tlisp/tlspec.html ).
I am writing a program that gets a natural number num and returns the sum of all numbers from 0 to num (inclusive) that are multiples of either 3 or 5.
I have the function that determines if its a multiple of 3 or 5 written, but the part I am stuck on is where I am trying to save all of the variables I loop through into 2 different lists.
For example, if I am given a number (like 5), I start with the number 5, and then submit the number into my function that determines whether its a multiple of 3 or 5. I want to store any variables returned as True to one list, then put any that are returned as NIL into another list. The problem is that I cant figure out how to call on a list that I previously created. The list needs to have all of the values from the previous times I called it as well.
How could I get this list problem fixed?
Upvotes: 0
Views: 224
Reputation: 71065
Start with this:
(defun sumx (n m) (sumx_aux n m ....... ))
(defun sumx_aux (n m x s) (if (> x n) s (sumx_aux n m (+ x m) ..... )))
What does this sumx
function do?
Fill in the blanks, figure out how you'd use it, and you're almost done. :)
If you need additional clues, read up on inclusion-exclusion principle. Basically, here it's about subtracting the numbers which were counted twice.
But if you insist on actually building your two lists, you'd do that by having two accumulating parameters in your recursive function, and adding a number you currently have to either one, or another, in two separate recursive calls inside if
's two clauses:
(defun foo_loop ( ... a b )
...
(if ...
(foo_loop ... (cons c a) b)
(foo_loop ... a (cons c b))))
Upvotes: 2