What is wrong with this Lisp Function? - function

This function is a CLisp function, this is part of a homework problem, but which is supposed to be written in this different format (the second function).
(defun range (m M) (cond
((> m M) '() )
((= m M) '() )
((< m M) (cons m (range (+ m 1) M ) ) )
)
)
(define (range m M) (cond
((> m M) '() )
((= m M) '() )
((< m M) (cons m (range (+ m 1) M ) ) )
)
)
These should both take a min value (m) and a max value (M) and return the list of integers from min to max (exluding the max value / M-1)
I have traced this over and over and I can't see why it is just returning NIL it must be a very dumb logic mistake.
(range 1 4) => result (1 2 3)
m=1 | M=4 ==> return (cons 1 (2 3) )
m=2 | M=4 ==> return (cons 2 (3) )
m=3 | M=4 ==> return (cons 3 () )
m=4 | M=4 ==> return ()
v ^
---------/
I'm going crazy trying to figure out WHY this is not performing like I trace it.
Again, when I execute the function it results in NIL.

I ran this using SBCL and it complained that the variable M appears twice in the parameter list. Lisp is not case-sensitive for variable names.
On changing it to
(defun range (m MM)
(cond
((> m MM) '() )
((= m MM) '() )
((< m MM) (cons m (range (+ m 1) MM)))))
It worked fine.
> (trace range)
> (range 1 4)
0: (RANGE 1 4)
1: (RANGE 2 4)
2: (RANGE 3 4)
3: (RANGE 4 4)
3: RANGE returned NIL
2: RANGE returned (3)
1: RANGE returned (2 3)
0: RANGE returned (1 2 3)
-> (1 2 3)
I checked with CLISP. With different variable names it works OK. CLISP does not pick up the error, unlike SBCL.
<[1]> (defun range (m MM) (cond ((>= m MM) '())((< m MM) (cons m (range (+ m 1) MM )))))
RANGE
[2]> (range 1 4)
(1 2 3)
Here is your version:
[3]> (defun range (m M) (cond ((>= m M) '())((< m M) (cons m (range (+ m 1) M)))))
RANGE
[4]> (range 1 4)
Nil

Related

Function to count number of 0 in given arguments in lisp

I want to create a function in LISP
to count the number of 0 in given arguments
Ex
(count_number_of_0 '(1 0 5 9 0 0 0 7 1 0) )
Output : 5
Here is an implementation in Racket, which is a lisp-family language. It would be quite easy to translate into Common Lisp (but a little more verbose in CL):
(define make-counter
(λ (v same?)
(λ (l)
((λ (c)
(c c 0 l))
(λ (c a t)
(if (null? t)
a
(c c (if (same? (first t) v) (+ a 1) a) (rest t))))))))
(define count-zeros
(make-counter 0 =))
And now
> (count-zeros '(1 2 0 3 4 0))
2
one way is:
(defun count-number-of-0 (lst &optional (cnt 0)) ;counter starts at zero
(if lst
(if (and (numberp (car lst)) ;better verify that element is a number
(= 0 (car lst)))
(progn
(setq cnt (+ cnt 1))
(count-number-of-0 (cdr lst) cnt))
(count-number-of-0 (cdr lst) cnt))
cnt)) ;return counter
This should work in all implementations of common-lisp.

Solving a functional programming problem using dr.racket

I am trying to implement a function called funPower, which takes a function f, an integer n and returns the function f^n. For example ((funPower sqrt 2) 16) should return 2, which is (sqrt (sqrt 16)).
This is what I have so far but it is not giving me correct output
(define (funPower f n)
(lambda(x) (if (<= n 1)
(f x)
(f (funPower f (- n 1)) x))))
First, you're missing one more pair of parens.
(define (funPower1 f n)
(lambda (x) (if (<= n 1)
(f x)
;; (f ( funPower1 f (- n 1)) x))))
(f ( ( funPower1 f (- n 1)) x)))) )
;; ^^^ ^^^
because (funPower1 f (- n 1)) returns a function to be called on x, the future argument value, as you show with the example, ((funPower sqrt 2) 16).
Second, it's <= 0, not <= 1, and the function f shouldn't be called at all in such a case:
(define (funPower2 f n)
(lambda (x) (if (<= n 0)
;; (f x) ^^^
x
(f ( ( funPower2 f (- n 1)) x)))) )
Now that it's working, we see that it defers the decisions to the final call time, of ((funPower f n) x). But it really could do all the decisions upfront -- the n is already known.
To achieve that, we need to swap the (lambda and the (funPower, to push the lambda "in". When we do, it'll become an additional argument to such augmented funPower:
(define (funPower3 f n)
(if (<= n 0) (lambda (x)
x )
(funPower3 f (- n 1) (lambda (x) (f x)))) )
Now this is completely out of sync. Where's that third argument?
(define (funPower4 f n fun)
(if (<= n 0) fun
(funPower4 f (- n 1) (lambda (x) (fun (f x)))) ))
That's a little bit better, but what's the fun, originally? Where does it come from? It must always be (lambda (x) x) at first or else it won't be right. The solution is to make it an internal definition and use that, supplying it the correct argument the first time we call it:
(define (funPower5 f n)
(define (loop n fun)
(if (<= n 0) fun
(loop (- n 1)
(lambda (x) (fun (f x))))))
(loop n (lambda (x) x)))
This kind of thing would normally be coded as a named let,
(define (funPower5 f n)
(let loop ((n n)
(fun (lambda (x) x)))
(if (<= n 0) fun
(loop (- n 1)
(lambda (x) (fun (f x)))))))
We could also try creating simpler functions in the simpler cases. For instance, we could return f itself if n is 1:
(define (funPower6 f n)
(cond
((zero? n) .....)
((= n 1) .....)
((< n 0) .....)
(else
(let loop ((n n)
(fun .....))
(if (= n .....) fun
(loop (- n 1)
(lambda (x) (fun (f x)))))))))
Complete it by filling in the blanks.
More substantive further improvement is to use exponentiation by repeated squaring -- both in constructing the resulting function, and to have it used by the function we construct!
try this:
(define funpow
(lambda (f n)
((lambda (s) (s s n (lambda (x) x)))
(lambda (s n o)
(if (zero? n)
o
(s s (- n 1)
(lambda (x)
(o (f x)))))))))
(define sqrt_2 (funpow sqrt 2))
(define pow2_2 (funpow (lambda (x) (* x x)) 2))
(sqrt_2 16)
(pow2_2 2)

What this functions in Scheme language do?

I'm a newbie and I didn't understand very well the language. Could anyone please explain to me what this functions do?
First function:
(define (x l)
(cond
((null? l) 0)
((list? (car l))
(+ (x (car l)) (x (cdr l))))
(else (+ 1 (x (cdr l))))
))
Second function:
(define (x l)
(cond
((null? l) 0)
((list? (car l))
(+ (x (car l)) (x (cdr l))))
(else (+ (car l) (x (cdr l)))
))
I do understand the begining but the conditions I didn't understand. Any help?
I will call your second function y.
Writing in pseudocode,
x [] -> 0
x [a . b] -> x a + x b , if list a
x [a . b] -> 1 + x b , else, i.e. if not (list a)
y [] -> 0
y [a . b] -> y a + y b , if list a
y [a . b] -> a + y b , else, i.e. if not (list a)
So for example,
x [2,3] = x [2 . [3]]
= 1 + x [3]
= 1 + x [3 . []]
= 1 + (1 + x [])
= 1 + (1 + 0 )
and
y [2,3] = y [2 . [3]]
= 2 + y [3]
= 2 + y [3 . []]
= 2 + ( 3 + y [])
= 2 + ( 3 + 0 )
See? The first counts something in the argument list, the second sums them up.
Of course both functions could be called with some non-list, but then both would just cause an error trying to get (car l) in the second clause, (list? (car l)).
You might have noticed that the two are almost identical. They both accumulates (fold) over a tree. Both of them will evaluate to 0 on the empty tree and both of them will sum the result of the same procedure on the car and cdr when the car is a list?. The two differ when the car is not a list and in the first it adds 1 for each element in the other it uses the element itself in the addition. It's possible to write the same a little more compact like this:
(define (sum l)
(cond
((null? l) 0) ; null-value
((not (pair? l)) l) ; term
(else (+ (sum (car l)) (sum (cdr l)))))) ; combine
Here is a generalisation:
(define (accumulate-tree tree term combiner null-value)
(let rec ((tree tree))
(cond ((null? tree) null-value)
((not (pair? tree)) (term tree))
(else (combiner (rec (car tree))
(rec (cdr tree)))))))
You can make both of your procedures in terms of accumulate-tree:
(define (count tree)
(accumulate-tree tree (lambda (x) 1) + 0))
(define (sum tree)
(accumulate-tree tree (lambda (x) x) + 0))
Of course you can make a lot more than this with accumulate-tree. It doesn't have to turn into an atomic value.
(define (double tree)
(accumulate-tree tree (lambda (x) (* 2 x)) cons '()))
(double '(1 2 ((3 4) 2 3) 4 5)) ; ==> (2 4 ((6 8) 4 6) 8 10)

change - to + in Common Lisp

Is there way to change - (minus) function to + (plus) function?
My homework is to implement sin calculation on Macluaurin series
sin(x) = x-(x^3/3!)+(x^5/5!) -(x^7/7!)+(x^9/9!)-...
Each article has different sign. This is my Lisp code
(defun sinMac (x series n plusminus)
(cond ((= series 0) 0)
(t (funcall plusminus
(/ (power x n) (factorial n))
(sinMac x (- series 1) (+ n 2) plusminus)))))
Is it possible to change plusminus to exchange sign? if I get '+ function send '- to next recursive call. From that call (got '-) I call '+ and so on...
You could do it with a circular list. Like so:
(defun sin-mac (x series n plus-minus)
(cond ((zerop series) 0)
(t (funcall (car plus-minus)
(/ (power x n) (factorial n))
(sin-mac x (1- series) (+ n 2) (cdr plus-minus))))))
(sin-mac x series 1 '#0=(+ - . #0#))
Or even better, wrap up the initial arguments using labels:
(defun sin-mac (x series)
(labels ((recur (series n plus-minus)
(cond ((zerop series) 0)
(t (funcall (car plus-minus)
(/ (power x n) (factorial n))
(recur (1- series) (+ n 2) (cdr plus-minus)))))))
(recur series 1 '#0=(+ - . #0#))))
If the function is a symbol, this is easy:
(defun next-function (function)
(ecase function
(+ '-)
(- '+)))
(defun sinMac (x series n plusminus)
(cond ((= series 0) 0)
(t (funcall plusminus
(/ (power x n) (factorial n))
(sinMac x
(- series 1)
(+ n 2)
(next-function plusminus))))))
I would not swap the function but just the sign. Using a loop for this also seems clearer to me (and is most likely more efficient, although there is still plenty of opportunity for optimization):
(defun maclaurin-sinus (x n)
"Calculates the sinus of x by the Maclaurin series of n elements."
(loop :for i :below n
:for sign := 1 :then (- sign)
:sum (let ((f (1+ (* 2 i))))
(* sign
(/ (expt x f)
(factorial f))))))
A few optimizations make this about 10 times faster (tested with n = 5):
(defun maclaurin-sinus-optimized (x n)
"Calculates the sinus of x by the Maclaurin series of n elements."
(declare (integer n))
(loop :repeat n
:for j :from 0 :by 2
:for k :from 1 :by 2
:for sign := 1 :then (- sign)
:for e := x :then (* e x x)
:for f := 1 :then (* f j k)
:sum (/ e f sign)))

Scheme - define variable as the result of a function?

The beginning of one of my programs results in an error. This is the problem area. I am trying to define a variable as the result of a recursive function.
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(define a1 (a1func (- n 1))))
if you were to give it say (test 10) the error would be:
procedure application: expected procedure, given: #<undefined>; arguments were: 9
I assumed this could be done in Scheme?? ideas?
In pure FP languages computations are done passing parameters to functions, which return some values as a result. You could bind the result of test in the function which called test:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(a1func (- n 1)))
(define (calltest x)
(define (r (test (+ 2 x))))
(- r 4))
Variables usually bound once and cannot be changed. A function must return the value, a result of expression, but (define a1 (a1func(- n 1))) is rather a definition, not an expression, so the correct code would be:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(define a1 (a1func(- n 1)))
a1)
And since defining variable and immediate returning it is meaningless, a more correct code would be:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(a1func(- n 1)))
If your scheme implementation support lisp macros then you can write this:
(define-macro (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
`(define a1 ,(a1func (- n 1))))
or using named let
(define-macro (test n)
`(define a1 ,(let a1func ((i (- n 1)))
(if (= i 1)
0
(+ (/ 1 i) (a1func (- i 1)))))))