Adding two lists - lisp

I want to add two lists : (1 2 3) and (5 3 4) should yield (6 5 7).
The function should add the elements on the corresponding position, so even if I would have (9 1 2) + ( 5 2 6) , it should yield (14 3 8).
My function
(defun add(l r)
(setf return-value '())
(loop for i from 0 to (- (length l) 1)
do (setf return-value (cons (+(nth i l)(nth i r)) return-value))
)
(reverse return-value)
)
How could I create a simmilar function which would subtract the lists ?

If you are allowed to use the standard functions, then mapcar is your friend:
(mapcar #'+ '(1 2 3) (9 7 5))
==> (10 9 8)
Similarly for -.
Your function suffers from quadratic performance - you should not be using nth.
You should also bind return-value with let.
You should also use nreverse instead of reverse since you are constructing a fresh list anyway.
The more idiomatic way to write your function is
(defun addl (l r)
(loop for x in l and y in r collect (+ x y)))

Polynomial arithmetic
This seems like a follow up to your previous question, Decompose a list of numbers into digits,. There, you had a list of digits numbers, and they were the ai of a polynomial of the form
∑i=0… 10iai
where the n numbers in your list are the values of a0 to an-1, and everything after that is presumed to be zero. You were asking for a way to normalize the values such that each ai was in the range [0,9]. My answer to that question showed a few ways to do that.
Now, once you view numbers as a polynomial of this form, it's easy to see that you can simply piecewise add and subtract coefficients to the get the right, if not yet normalized, coefficients of the sum or difference. E.g.,
378 = 8 + 7×10 + 3×100→ (8 7 3)
519 = 9 + 1×10 + 5×100→ (9 1 5)
The sum is simply
(8+9) + (7+1)×10 + (3+5)×100 →(mapcar '+ x y) (17 8 8) →(number->digits (digits->number …)) (7 9 8)
The difference is simply
(8-9) + (7-1)×10 + (3-5)×100 →(mapcar '- x y) (-1 6 -2) →??? ???
What we don't have here is an appropriate normalization procedure. The one provided in the previous question doesn't work here. However, the list of digits is still correct, insofar as coefficients go, and the digits->number procedure produces the correct value of -141.
So, while you'll need to rethink what it means to show a list of digits for a negative number, you can do the correct type of addition and subtraction on your lists with the following, as long as both lists have the same length. If they don't have the same length, you'll need to pad the shorter one with zeros. A reimplementation of mapcar that supports this sort of operation might be useful here.
(defun sum (x y)
(mapcar '+ x y))
(defun difference (x y)
(mapcar '- x y))

Related

How to display first N natural numbers, knowing the divisors in Lisp

Display first N natural numbers, the divisors of which are only 2, 3 and 7.
I wrote something like that. I am a beginner in Lisp. Thank you!
defvar x 1
(defun numbers(n)
if(mod x 2 )
(loop for x from 1 to n
do(print x)
)
)
print(numbers())
Because I just had some time, you could have a look at this. Might not be the perfect solution but should be a good starting point for a beginner. Check out the books in the info tab to get into the syntax etc.
(defun divisible-by (n m)
"Returns T if N is evenly divisible by M."
(zerop (mod n m)))
(defun numbers (n)
"Print all number upto N which are divisible by 2, 3 and 7."
(loop
for i from 1 upto N
if (and (divisible-by i 2) (divisible-by i 3) (divisible-by i 7))
do (format t "~D~%" i)))

What is the difference between the two summation functions in Common Lisp, thanks

Both code examples are the for the summation formula:
Code example 1
(defund sigma (func n)
(cond ((= n 1)(funcall func 1)
(t (+ (sigma func(1- n))
(funcal func n))))))
Code example 2
(defund sigma(n)
(cond ((= n 1)1)
(t (+ n(sigma func(1- n))))
Both code examples are the for the summation formula
No they do not. While the second sums the numbers, the first calls a function with the number as argument and sums the result.
It would have f(i) instead of just i after the sigma in the mathematical notation. In higher order function lingo it is a term function. Here are some examples using 10:
(sigma (lambda (v) 1) 10) ; ==> 10 in CL I'd use (sigma (constantly 1) 10)
(sigma #'1+ 10) ; ==> 65
(sigma #'identity 10) ; ==> 55
The second would only produce the third example:
(sigma 10) ; ==> 55
PS: Your functions have syntax errors and typos I have just ignored. You'lll need to fix these before it works. The hardest one is perhaps the missing ending parenthesis in the first cond term making the cond only have one term and the second function also passing func, which doesn't make sense since its version only takes one argument.

Members in a list - LISP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need to write a program in Lisp to see the number of occurrences of a specific character in a list. For example the occurrences of 1 in the following list [1, 2, 3, 1,1]
A list in Lisp is a sequence of cons nodes: pairs of pointers - the first to the payload datum, and the second to the rest of the list. E.g. for [1,2,3,1,1],
.
/ \
1 .
/ \
2 .
/ \
3 ...... .
/ \
1 NIL
NIL is a special value signaling the empty list, such that the system knows not to try to explore it any further. In Scheme,
(define NIL '())
Recursive list processing paradigm is captured by the notion of fold, where each node . is "replaced" with a binary function f, and the special node NIL is replaced with some special "zero" value z, to create an application chain (f 1 (f 2 (f 3 (... (f 1 z) ...)))). In Scheme,
(define (myfold f z list)
(cond
((null? list) z) ; replace NIL with the initial ("zero") value
(else
(f ; combine
(car list) ; the payload datum, and the delayed,
(lambda () ; by creating a function to calculate it,
(myfold f z ; result of recursively folding
(cdr list))))))) ; the rest of list
That way, the combining function f must process two values: one is a node's payload datum, the other is the (delayed) result of recursively folding, with the same f and z, the rest of the list after that node.
(define (keep-equals v list)
(myfold
(lambda (a r) ; combine ...
(if (equal? v a)
(cons a ... ) ; the same thing goes over the dots, here
... )) ; and here
'() ; replace the NIL of the argument list with this
list))
Since the recursive folding results' calculation is delayed by creating a function to-be-called when the results are needed, we need to "force" that calculation to be performed, when we indeed need those results, by calling that function.
And if you want to count the number of occurrences instead of collecting them in a list, you just need to use a different combining function with a different initial ("zero") value.
In particular, we build a list by consing a value onto the rest of list (with NIL as the initial value, the empty list); whereas we count by incrementing a counter (with 0 as the initial value of that counter).
Calculating e.g. a list's length by folding, we essentially turn its elements each into 1: length [a,b,c,d,e] == 1 + (1 + (1 + (1 + (1 + 0)))). Here, the combining function will need to increment the counter conditionally, only when the payload data are such that we want to count them.
I like pretty well the answers already posted to this question. But it seems like they both involve a fair bit more than the necessary amount of work. On the other hand, given all the thought everyone's put into this, I'm almost embarrassed of how simple my answer is. Anyway, here's what I did:
(defun count-things-in (needle haystack)
"Count the number of NEEDLEs in HAYSTACK."
(reduce '+
(map 'list
#'(lambda (straw)
(if (equalp straw needle) 1 0))
haystack)))
(count-things-in 1 '(1 2 3 1 1))
;; => 3
It's pretty straightforward: you just map over HAYSTACK a function which returns 1 for an element which is EQUALP to NEEDLE or 0 for an element which isn't, and then reduce the resulting list by +. For the given example list, the map operation results in a list (1 0 0 1 1), which the reduce operation then treats as (1 + (0 + (0 + (1 + 1)))), which evaluates to 3.
Benefits of this approach include the use of an equality predicate loose enough to work with strings as well as numbers, and with numbers of different types but the same value -- that is, (equalp 1 1.0) => t; if you desire different behavior, use another equality predicate instead. Using the standard MAP and REDUCE functions, rather than implementing your own, also gives you the benefit of whatever optimizations your Lisp system may be able to apply.
Drawbacks include being not nearly as impressive as anyone else's implementation, and being probably not low-level enough to satisfy the requirements of the asker's homework problem -- not that that latter especially dismays me, given that this answer does satisfy the stated requirement.
I'm new to lisp myself but here is how I would do it. I haven't looked at the other answer yet from Will so I'll check that out after I post this. The member function has the utility of both telling you if it found something in a list, and also returning the rest of that list starting from where it found it:
CL-USER> (member '1 '(0 1 2 3))
(1 2 3)
You could then recursively call a function that uses member and increment a counter from returned values in a variable from a let:
(defun find1 (alist)
(let ((count 0))
(labels ((findit (list)
(let ((part (member '1 list)))
(if part
(progn (incf count)
(findit (rest part)))
0))
count))
(findit alist))))
Here is the result:
CL-USER> (find1 '(1 2 3 4 5))
1
CL-USER> (find1 '(1 1 2 3 4 5))
2
CL-USER> (find1 '(1 1 1 2 3 1 4 5 1 1))
6
You could get rid of that unattractive progn by using cond instead of if
UPDATE: Here is an updated and more elegant version of the above, based on the comments, that I think would qualify as tail recursive as well:
(defun find1 (alist &optional (accum 0))
(let ((part (member '1 alist)))
(if part
(find1 (rest part) (+ accum 1))
accum)))
Here it is in action:
CL-USER> (find1 '(1 2 3 4))
1
CL-USER> (find1 '(1 1 1 1))
4
CL-USER> (find1 '(1 1 0 1 1))
4
CL-USER> (find1 '(0 2 1 0 1 1 0 1 1))
5

multiplication of empty list in emacs lisp

Why in lisp (Emacs Lisp and Scheme as I know) construction like (*) returns 1?
What I multiply here? How can I call this function * without arguments?
This is a mathematical convention: the product of an empty sequence of numbers is one, by definition; note that one is the identity element for multiplication (1×a = a×1 = a). This is convenient because you can call * with a variable number of arguments without worrying about the case where there are no arguments present.
Similarly, the sum of an empty sequence of numbers is zero, the identity element for addition. Try issuing (+) at your Lisp prompt.
It's a property inherited from mathematics. It's like addition, you can add together any number of numbers, with the special case that adding no numbers together give you the sum zero.
Likewise for multiplication, if you multiply an arbitrary number of numbers, you will get the product. To get this to work for no numbers, 1 is used as the base value (which has some fancy name in mathematics, which I have forgotten many years ago).
So, do you have any practical use for this in a programming language. Yes, as you can call a functions like + and * with arbitrary number of arguments, I would say yes. For example:
(apply '+ '(2 3 4)) => 9
(apply '+ '(2 3)) => 5
(apply '+ '(2)) => 2
(apply '+ '()) => 0
(apply '* '(2 3 4)) => 24
(apply '* '(2 3)) => 6
(apply '* '(2)) => 2
(apply '* '()) => 1

help with multiplying polynomials in lisp

for example: (3x2 - 5x + 2)(7x + 1) and you simplify it like this:
((3 2)(-5 1)(2 0))((7 1)(1 0))
((21 3)(3 2)(-35 2)(-5 1)(14 1)(2 0))
(21 3)(32 2)(9 1)(2 0)
and you get this answer: 21x3 + 32x2 + 9x + 2
i need this solution in lisp please help
For the first stage, you need to pair up every LHS component with every RHS component; a cartesian product of the two sets. This requires a two-level map followed by a concatenation of the second-level lists of pairs into a single top level list (think (apply #'append ...).
The second stage can be done with a reduce that builds up an association list, keyed on the exponent.
EDIT: Let me solve a different problem for you, and let you figure out how to translate it into the solution for your problem:
Compute (a + b + ... + k) * (l + m + ... + z) by first expanding into pairs and then summing the products:
(defun mul-sums (aa bb)
(reduce #'+
(apply #'append
(map 'list
#'(lambda (a)
(map 'list
#'(lambda (b)
(* a b))
bb))
aa))))
; Compute (1 + 2 + 3) * (3 + 4).
> (mul-sums '(1 2 3) '(3 4))
42