Exclusive OR in Scheme - lisp

What is the exclusive or functions in scheme? I've tried xor and ^, but both give me an unbound local variable error.
Googling found nothing.

I suggest you use (not (equal? foo bar)) if not equals works. Please note that there may be faster comparators for your situiation such as eq?

As far as I can tell from the R6RS (the latest definition of scheme), there is no pre-defined exclusive-or operation. However, xor is equivalent to not equals for boolean values so it's really quite easy to define on your own if there isn't a builtin function for it.
Assuming the arguments are restricted to the scheme booleans values #f and #t,
(define (xor a b)
(not (boolean=? a b)))
will do the job.

If you mean bitwise xor of two integers, then each Scheme has it's own name (if any) since it's not in any standard. For example, PLT has these bitwise functions, including bitwise-xor.
(Uh, if you talk about booleans, then yes, not & or are it...)

Kind of a different style of answer:
(define xor
(lambda (a b)
(cond
(a (not b))
(else b))))

Reading SRFI-1 shed a new light upon my answer. Forget efficiency and simplicity concerns or even testing! This beauty does it all:
(define (xor . args)
(odd? (count (lambda (x) (eqv? x #t)) args)))
Or if you prefer:
(define (true? x) (eqv? x #t))
(define (xor . args) (odd? (count true? args)))

(define (xor a b)
(and
(not (and a b))
(or a b)))

Since xor could be used with any number of arguments, the only requirement is that the number of true occurences be odd. It could be defined roughly this way:
(define (true? x) (eqv? x #t))
(define (xor . args)
(odd? (length (filter true? args))))
No argument checking needs to be done since any number of arguments (including none) will return the right answer.
However, this simple implementation has efficiency problems: both length and filter traverse the list twice; so I thought I could remove both and also the other useless predicate procedure "true?".
The value odd? receives is the value of the accumulator (aka acc) when args has no remaining true-evaluating members. If true-evaluating members exist, repeat with acc+1 and the rest of the args starting at the next true value or evaluate to false, which will cause acc to be returned with the last count.
(define (xor . args)
(odd? (let count ([args (memv #t args)]
[acc 0])
(if args
(count (memv #t (cdr args))
(+ acc 1))
      acc))))

> (define (xor a b)(not (equal? (and a #t)(and b #t))))
> (xor 'hello 'world)
$9 = #f
> (xor #f #f)
$10 = #f
> (xor (> 1 100)(< 1 100))
$11 = #t

I revised my code recently because I needed 'xor in scheme and found out it wasn't good enough...
First, my earlier definition of 'true? made the assumption that arguments had been tested under a boolean operation. So I change:
(define (true? x) (eqv? #t))
... for:
(define (true? x) (not (eqv? x #f)))
... which is more like the "true" definition of 'true? However, since 'xor returns #t if its arguments have an 'odd? number of "true" arguments, testing for an even number of false cases is equivalent. So here's my revised 'xor:
(define (xor . args)
(even? (count (lambda (x) (eqv? x #f)) args)))

Related

How do I pass in a list of list into a function?

(defun square (n) (* n n))
(defun distance (a b)
(let (
(h (- (second b) (second a)))
(w (- (first b) (first a))))
(sqrt (+ (square h) (square w)))
)
)
(defun helper-2 (head)
(if (null (first (rest head))))
0
(+
(distance (car head) (first (rest head)))
(helper-2 (rest head))
)
I have this code written. My question is how do I use the helper-2 method? I've tried
(helper-2 '((2 0) (4 0)))
(helper-2 '(2 0) '(4 0)) neither works. Could anyone help? Thanks.
Please cut and paste the code in my previous answer and use it verbatim. Here, you've actually made some changes to the code to make it incorrect: instead of your original one-armed if, you've made it even worse, a zero-armed if.
A correctly-formatted two-armed if expression looks like this (noting that expr1 and expr2 are supposed to be flush with (indented to the same level as) test):
(if test
expr1
expr2)
This means that if test evaluates to a truthy value (anything other than nil), then expr1 is evaluated, and its value is the value of the if expression; otherwise expr2 is used instead. In the code snippet I had, test is (null (first (rest list))), expr1 is 0, and expr2 is (+ (distance (car list) (first (rest list))) (helper-2 (rest list))).
The other nice thing about using my code snippet directly is that it's already formatted correctly for standard Lisp style, which makes it much more pleasant for other Lisp programmers to read.

LISP - count occurences of every value in a list

I apologize for the bad English..
I have a task to write a function called "make-bag" that counts occurences of every value in a list
and returns a list of dotted pairs like this: '((value1 . num-occurences1) (value2 . num-occurences2) ...)
For example:
(make-bag '(d c a b b c a))
((d . 1) (c . 2) (a . 2) (b . 2))
(the list doesn't have to be sorted)
Our lecturer allows us to us functions MAPCAR and also FILTER (suppose it is implemented),
but we are not allowed to use REMOVE-DUPLICATES and COUNT-IF.
He also demands that we will use recursion.
Is there a way to count every value only once without removing duplicates?
And if there is a way, can it be done by recursion?
First of, I agree with Mr. Joswig - Stackoverflow isn't a place to ask for answers to homework. But, I will answer your question in a way that you may not be able to use it directly without some extra digging and being able to understand how hash-tables and lexical closures work. Which in it's turn will be a good exercise for your advancement.
Is there a way to count every value only once without removing duplicates? And if there is a way, can it be done by recursion?
Yes, it's straight forward with hash-tables, here are two examples:
;; no state stored
(defun make-bag (lst)
(let ((hs (make-hash-table)))
(labels ((%make-bag (lst)
(if lst
(multiple-value-bind (val exists)
(gethash (car lst) hs)
(if exists
(setf (gethash (car lst) hs) (1+ val))
(setf (gethash (car lst) hs) 1))
(%make-bag (cdr lst)))
hs)))
(%make-bag lst))))
Now, if you try evaluate this form twice, you will get the same answer each time:
(gethash 'a (make-bag '(a a a a b b b c c b a 1 2 2 1 3 3 4 5 55)))
> 5
> T
(gethash 'a (make-bag '(a a a a b b b c c b a 1 2 2 1 3 3 4 5 55)))
> 5
> T
And this is a second example:
;; state is stored....
(let ((hs (make-hash-table)))
(defun make-bag (lst)
(if lst
(multiple-value-bind (val exists)
(gethash (car lst) hs)
(if exists
(setf (gethash (car lst) hs) (1+ val))
(setf (gethash (car lst) hs) 1))
(make-bag (cdr lst)))
hs)))
Now, if you try to evaluate this form twice, you will get answer doubled the second time:
(gethash 'x (make-bag '(x x x y y x z z z z x)))
> 5
> T
(gethash 'x (make-bag '(x x x y y x z z z z x)))
> 10
> T
Why did the answer doubled?
How to convert contents of a hash table to an assoc list?
Also note that recursive functions usually "eat" lists, and sometimes have an accumulator that accumulates the results of each step, which is returned at the end. Without hash-tables and ability of using remove-duplicates/count-if, logic gets a bit convoluted since you are forced to use basic functions.
Well, here's the answer, but to make it a little bit more useful as a learning exercise, I'm going to leave some blanks, you'll have to fill.
Also note that using a hash table for this task would be more advantageous because the access time to an element stored in a hash table is fixed (and usually very small), while the access time to an element stored in a list has linear complexity, so would grow with longer lists.
(defun make-bag (list)
(let (result)
(labels ((%make-bag (list)
(when list
(let ((key (assoc (car <??>) <??>)))
(if key (incf (cdr key))
(setq <??>
(cons (cons (car <??>) 1) <??>)))
(%make-bag (cdr <??>))))))
(%make-bag list))
result))
There may be variations of this function, but they would be roughly based on the same principle.

LISP functions that perform both symbolic and numeric operations on expressions using +, -, *, and /

I'm currently working on a LISP exercise for a small project and need severe help. This may be more or less of a beginner's question but I'm absolutely lost on writing a certain function that takes in two unevaluated functions and spits out the result dependent on if the variables were given an assignment or not.
An example would be
(setq p1 '(+ x (* x (- y (/ z 2)))))
Where
(evalexp p1 '( (x 2) (z 8) ))
returns (+ 2 (* 2 (- y 4)))
My goal is to write the evalexp function but I can't even think of where to start.
So far I have
(defun evalexp (e b) )
.. not very much. If anyone could please help or lead me in a good direction I'd be more than appreciative.
Here's a full solution. It's pretty straightforward, so I'll leave out a full explanation. Ask me in the comments if there's anything you can't figure out yourself.
(Using eval to do the actual evaluation might not be what you want in your exercise/project. Look up "meta-circular interpreter" for another way.)
(defun apply-env (exp env)
(reduce (lambda (exp bdg) (subst (cadr bdg) (car bdg) exp))
env :initial-value exp))
(defun try-eval (exp)
(if (atom exp)
exp
(let ((exp (mapcar #'try-eval exp)))
(if (every #'numberp (cdr exp))
(eval exp)
exp))))
(defun evalexp (exp env)
(try-eval (apply-env exp env)))
Here's a hint, this is how you might do it (in pseudocode):
function replace(vars, list):
for each element of list:
if it's an atom:
if there's an association in vars:
replace atom with value in vars
else:
leave atom alone
else:
recursively apply replace to the sublist
There will certainly be some details to work out as you convert this to Lisp code.

Scheme/Racket: do loop order of evaluation

The following procedure is valid in both scheme r6rs and Racket:
;; create a list of all the numbers from 1 to n
(define (make-nums n)
(do [(x n (- x 1)) (lst (list) (cons x lst))]
((= x 0)
lst)))
I've tested it for both r6rs and Racket and it does work properly, but I only know that for sure for DrRacket.
My question is if it is guaranteed that the step expressions ((- x 1) and (cons x lst) in this case) will be evaluated in order. If it's not guaranteed, then my procedure isn't very stable.
I didn't see anything specifying this in the standards for either language, but I'm asking here because when I tested it was evaulated in order.
They're generally not guaranteed to be evaluated in order, but the result will still be the same. This is because there are no side-effects here -- the loop doesn't change x or lst, it just rebinds them to new values, so the order in which the two step expressions are evaluated is irrelevant.
To see this, start with a cleaner-looking version of your code:
(define (make-nums n)
(do ([x n (- x 1)] [lst null (cons x lst)])
[(zero? x) lst]))
translate to a named-let:
(define (make-nums n)
(let loop ([x n] [lst null])
(if (zero? x)
lst
(loop (- x 1) (cons x lst)))))
and further translate that to a helper function (which is what a named-let really is):
(define (make-nums n)
(define (loop x lst)
(if (zero? x)
lst
(loop (- x 1) (cons x lst))))
(loop n null))
It should be clear now that the order of evaluating the two expressions in the recursive loop call doesn't make it do anything different.
Finally, note that in Racket evaluation is guaranteed to be left-to-right. This matters when there are side-effects -- Racket prefers a predictable behavior, whereas others object to it, claiming that this leads people to code that implicitly relies on this. A common small example that shows the difference is:
(list (read-line) (read-line))
which in Racket is guaranteed to return a list of the first line read, and then the second. Other implementations might return the two lines in a different order.

What is the Scheme function to find an element in a list?

I have a list of elements '(a b c) and I want to find if (true or false) x is in it, where x can be 'a or 'd, for instance. Is there a built in function for this?
If you need to compare using one of the build in equivalence operators, you can use memq, memv, or member, depending on whether you want to look for equality using eq?, eqv?, or equal?, respectively.
> (memq 'a '(a b c))
'(a b c)
> (memq 'b '(a b c))
'(b c)
> (memq 'x '(a b c))
#f
As you can see, these functions return the sublist starting at the first matching element if they find an element. This is because if you are searching a list that may contain booleans, you need to be able to distinguish the case of finding a #f from the case of not finding the element you are looking for. A list is a true value (the only false value in Scheme is #f) so you can use the result of memq, memv, or member in any context expecting a boolean, such as an if, cond, and, or or expression.
> (if (memq 'a '(a b c))
"It's there! :)"
"It's not... :(")
"It's there! :)"
What is the difference between the three different functions? It's based on which equivalence function they use for comparison. eq? (and thus memq) tests if two objects are the same underlying object; it is basically equivalent to a pointer comparison (or direct value comparison in the case of integers). Thus, two strings or lists that look the same may not be eq?, because they are stored in different locations in memory. equal? (and thus member?) performs a deep comparison on lists and strings, and so basically any two items that print the same will be equal?. eqv? is like eq? for almost anything but numbers; for numbers, two numbers that are numerically equivalent will always be eqv?, but they may not be eq? (this is because of bignums and rational numbers, which may be stored in ways such that they won't be eq?)
> (eq? 'a 'a)
#t
> (eq? 'a 'b)
#f
> (eq? (list 'a 'b 'c) (list 'a 'b 'c))
#f
> (equal? (list 'a 'b 'c) (list 'a 'b 'c))
#t
> (eqv? (+ 1/2 1/3) (+ 1/2 1/3))
#t
(Note that some behavior of the functions is undefined by the specification, and thus may differ from implementation to implementation; I have included examples that should work in any R5RS compatible Scheme that implements exact rational numbers)
If you need to search for an item in a list using an equivalence predicate different than one of the built in ones, then you may want find or find-tail from SRFI-1:
> (find-tail? (lambda (x) (> x 3)) '(1 2 3 4 5 6))
'(4 5 6)
Here's one way:
> (cond ((member 'a '(a b c)) '#t) (else '#f))
#t
> (cond ((member 'd '(a b c)) '#t) (else '#f))
#f
member returns everything starting from where the element is, or #f. A cond is used to convert this to true or false.
You are looking for "find"
Basics - The simplest case is just (find Entry List), usually used as a predicate: "is Entry in List?". If it succeeds in finding the element in question, it returns the first matching element instead of just "t". (Taken from second link.)
http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node145.html
-or-
http://www.apl.jhu.edu/~hall/Lisp-Notes/Higher-Order.html
I don't know if there is a built in function, but you can create one:
(define (occurrence x lst)
(if (null? lst) 0
(if (equal? x (car lst)) (+ 1 (occurrence x (cdr lst)))
(occurrence x (cdr lst))
)
)
)
Ỳou will get in return the number of occurrences of x in the list. you can extend it with true or false too.
(define (member? x list)
(cond ((null? list) #f)
((equal? x (car list)) #t)
(else (member? x (cdr list)))))
The procedure return #t (true) or #f (false)
(member? 10 '(4 2 3))
output is #f