Get result with list - list

;How to get the value of 'a' in 'b'?
;Not want to assign the letter 'a' in 'b' want the value contained in 'a'
(define a 5)
(define c '(a c))
(define b (car c))
(display b)

(define a 5)
(define c (list a 'c))
(define b (car c))
(display b)
' is equivalent to the quote procedure. So '(a c) => (list 'a 'c)
See: http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/Quoting.html#Quoting
Or, using your original code, are you asking how you would (eval b (the-environment))?

Related

What is the result of this in scheme: (cdr '((a b c d)))

Isn't it supposed to be (a b c d) ??
When I try it on Racket it gives me () .
'((a b c d)) is a list, containing only one element, that is the four-element list (a b c d). So if you get the car of it, you obtain as result (a b c d), while the cdr produces correctly the empty list ().
How would you create such a list using cons?
(cons (cons 'a (cons 'b (cons 'c (cons 'd '()))))
'())
or
(cons '(a b c d) '())
cdr returns the second element of the given pair, so it returns '().

Racket/Scheme - checking to see if a list is a sublist of another list

I'm new to coding in racket, but I wanted to define a procedure that checks to see if a given list is a sublist (or part of) another list.
This is my code so far:
(define prefix?
(lambda (lst1 lst2)
(cond
((equal? lst1 lst2) #t)
((null? lst2) #f)
(else (prefix? lst1 (reverse (rest (reverse lst2))))))))
(define sublist?
(lambda (lst1 lst2)
(cond
((prefix? lst1 lst2) #t)
((null? lst2) #f)
(else (prefix? lst1 (rest lst2))))))
I've tried most cases and it works the way it's supposed to but when I tried this test case:
(sublist? '(a b d) '(a b c a b d e))
It returns #f when it's supposed to return #t
I tried tracing the sublist? procedure but it isn't returning me any useful information.
Is there a logic error in my code?
There is a logic error. The default case of sublist? should call sublist?, but instead calls prefix? so your prefix? will only be true if the match is either in index 0 or 1.
Also you have created a rather complex prefix?. Instead of comparing one by one element until any of them are empty you do a O(n) removal of the last element until you have a empty list before returning #f even if the two first elements are different. I would have compared the first elements and then recurred with rest in both args until either list is empty. Which one depends on the result and eg. (prefix '(a b) '(w a d f s)) will stop computing after the very first check between a and w.
try this:
(define sub?
(lambda (l sub)
(define test (lambda (x) (equal? x sub)))
((lambda (s) (s s l test))
(lambda (s l k)
(or (k '())
(and (pair? l)
(s s (cdr l)
(lambda (r)
(or (test r)
(k (cons (car l) r)))))))))))
(sub? '(a b c a b d e) '(b d e) )
(sub? '(a b c a b d e) '(c a b) )
(sub? '(a b c a b d e) '(a b c) )
(sub? '(a b c a b x e) '(a b d) )

Rearranging list into left-normal form in Racket

I was going to post this to the codereview stackexchange but I saw that you should only post working code. I asked this question earlier: Reordering parentheses using associative property in Racket
In case you don't check the link basically I want to rearrrange a list of symbols so that this:
'((a + b) + c) -> '(a + (b + c))
or this:
'((a + b) + (c + d)) -> '(a + (b + (c + d)))
This is the code I've written so far:
(define (check? expr)
(display expr)
(newline)
(cond ((null? expr) -1)
((and (atom? (car expr)) (atom? (cadr expr))) 0) ;case 0
((and (atom? (car expr)) (list? (cadr expr))) 1) ;case 1
((and (list? (car expr)) (null? (cdr expr))) (check? (car expr))) ;nested expression for example '((a b))
((and (list? (car expr)) (atom? (cadr expr))) 2) ;case 2
((and (list? (car expr)) (list? (cadr expr))) 3) ;case 3
(else -1)))
(define (rewrite x)
(display (check? x))
(newline)
(cond ((null? x))
((atom? x) x)
((= 0 (check? x)) x) ;case 0 is '(a + b)
((= 1 (check? x)) (cons (car x) (rewrite (cdr x)))) ;case 1 is '(a + (b + c))
((= 2 (check? x)) (rewrite (list (caar x) (cons (cadar x) (cdr x))))) ;case 2 is ((b + c) + a)
((= 3 (check? x)) (rewrite ((list (caar x) (cons (cadar x) (cdr x))))))));case 3 is ((a + b) + (c + d))
;(rewrite '(((d c) b) a))
(rewrite '(a b))
(rewrite '(a (b c)))
(rewrite '((a b) (c d)))
Am I on the right track? If not does anyone have any pointers? Am I creating the lists wrong? If you need any more information let me know or if I should comment the code better also let me know.
In case you don't check the earlier question, this is the answer I got (which was very helpful):
var -> var
(var + var) -> (var + var)
(var + (fip1 + fpip2)) -> (var + (REWRITE (fip1 + fpip2))
((fip1 + fpip2) + var) -> (REWRITE (fip1 + (fip2 + var))
((fip1 + fpip2) + (fip3 + fpip4)) -> (REWRITE (fip1 + (fip2 + (fip3 + fip4))))
The following is the grammar you have defined for your syntax:
var ::= a | b | c | d | e | f | g
fpip ::= var | (fpip + fpip)
As such, we can start by defining predicates that test whether a given expression is valid or not, using the rules set above:
(define (var? e)
(member e '(a b c d e f g)))
(define (fpip? e)
(cond
((var? e) #t)
((or (not (pair? e))
(null? e)
(null? (cdr e))
(null? (cddr e))
(not (null? (cdddr e))))
#f)
(else (and (fpip? (car e))
(equal? (cadr e) '+)
(fpip? (caddr e))))))
Now we can say, for example:
> (fpip? 'a)
#t
> (fpip? '((a + b) + c))
#t
> (fpip? '((+(d + e) + f) + (a + (a + c))))
#f
With that in place, rewrite can be written as the right-associative form of an expression, if the expression is valid fpip, and #f otherwise:
(define (rewrite e)
(if (not (fpip? e))
#f
(rewrite-fpip e)))
Next, we will define rewrite-fpip to be a procedure that accepts and transforms any valid fpip, as follows:
(define (rewrite-fpip e)
(cond
((not (pair? e)) e) ;; var
((not (pair? (car e)))
(list (car e) '+ (rewrite-fpip (caddr e)))) ;; (var + fpip)
(else
(rewrite-fpip ;; (fpip + fpip)
(list (caar e) '+ (list (caddar e) '+ (caddr e)))))))
Thus we can have:
> (rewrite 'a)
'a
> (rewrite '((a + b) + c))
'(a + (b + c))
> (rewrite '((a + b) + (c + d)))
'(a + (b + (c + d)))
> (rewrite '(((d + e) + f) + (a + (a + c))))
'(d + (e + (f + (a + (a + c)))))
That they tell you not to use the flattening in your solution doesn't mean you can't use the flattening in the derivation of your solution.
Writing in an imaginary pattern-matching equational pseudocode (because it is much shorter and visually apparent, i.e. easier to follow),
flatten a = flatten2 a [] ; [] is "an empty list"
flatten2 (a+b) z = flatten2 a (flatten2 b z) ; if it matches (a+b)
flatten2 a [] = a ; if it doesn't, and the 2nd is []
flatten2 a b = a + b ; same, and the 2nd arg is not []
Oh wait, I'm not flattening it here, I am building the normalized sum expressions here!
The only problem with this approach is the needless check for [] repeated over and over when we know it will only ever be true once -- it is we who write this code after all.
Fusing this knowledge in, we get
normalize a = down a ; turn EXPR ::= ATOM | EXPR + EXPR
down (a + b) = up a (down b)
down a = a ; into NormExpr ::= ATOM | ATOM + NormExpr
up (a + b) z = up a (up b z)
up a b = a + b
Now all's left is to code this up in regular Scheme. Scheme also has the advantage that the test can be much simplified to just
(define (is-sum? a+b) (pair? a+b))
edit: The final function from the other answer in the same pseudocode is:
rewrite ((a + b) + c) = rewrite (a + (b + c)) ; rotate right!
rewrite (a + b) = a + rewrite b ; go in, if the first rule didn't match
rewrite a = a ; stop, if the first two didn't match
It rearranges the + nodes' tree structure before starting the work1, whereas the solution in this answer follows the input structure while transforming it. As the result, thanks to the nested recursion the run time stack will only be as deep as the input structure, whereas with rewrite it will always be n levels deep at the deepest point, when the list is fully linearized on the stack (in the second rule), just before the sums are assembled on the way back up.
But the first rule in rewrite is tail recursive, and the second is tail recursive modulo cons, so rewrite can be rewritten in a tail-recursive style as a whole, with few standard modifications. Which is definitely a plus.
On the other hand this new code will have to surgically modify (i.e. mutate) the + nodes (see the Wikipedia article linked above, for details), so you'll have to choose your implementation of this data type accordingly. If you use lists, this means using set-car! and/or set-cdr!; otherwise you can implement them as Racket's #:mutable structures. When the result is built, you could convert it to a regular list with an additional O(n) traversal, if needed.
1 reminiscent of the old gopher trick from John McCarthy, burrowing into the input structure, with reified continuations.

implement equal function to recursion function

I want to fix my own function that gives the same result with the default intersection function. I've been trying to write a lisp code which prints same elements in the two lists. My code works for it. But it doesn't work for nested lists. How can I fix this?
(defun printelems (L1 L2)
(cond
((null L1) nil) ((member (first L1) L2) (cons (first L1) (printelems (rest L1) L2)))
(t (printelems (rest L1) L2))))
Expected inputs and outputs
(printelems '(2 3 5 7) '( 2 3)) => It works
=> (2 3)
(printelems '(a b '(c f)) '(a d '(c f) e)) => It doesn't work.
=> (a (c f))
Edit
Using the default intersection function works as intended. How can I use the equal function in my recursive function?
For default intersection,
(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
((C F) A)
(intersection '(a b (c f)) '(a d c f e) :test 'equal)
(A)
My intersection,
(printelems '(a b (c f)) '(a d c f e))
(A C F)
(printelems '(a b (c f)) '(a d (c f) e) )
(A C F)
My edited code:
(defun flatten (l)
(cond ((null l) nil)
((atom (car l)) (cons (car l) (flatten (cdr l))))
(t (append (flatten (car l)) (flatten (cdr l))))))
(defun printelemsv1(list1 list2)
(cond
((null list1) nil)
(((member (first list1) list2) (cons (first list1) (printelemsv1 (rest list1) list2)))
(t (printelemsv1 (rest list1) list2)))))
(defun printelems (L1 L2)
(printelemsv1 (flatten L1) (flatten L2)))
Common Lisp already has an intersection function. If you want to compare sublists like (C F), you'll want to use equal or equalp as the test argument.
(intersection '(a b '(c f)) '(a d '(c f) e) :test 'equal)
;=> ('(C F) A)
While it doesn't change how intersection works, you probably don't really want quote inside your list. Quote isn't a list creation operator; it's a "return whatever the reader read" operator. The reader can read (a b (c f)) as a list of two symbols and a sublist, so (quote (a b (c f))), usually abbreviated as '(a b (c f)) is fine. E.g.:
(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
;=> ((C F) A)
It's always helpful when you provide an example of input and the expected output. I assume you mean you have two lists like '(1 (2 3) 4) and '((1) 2 5 6) that the function should produce '(1 2). In this case you can just flatten the two lists before giving them to printelems.
Since I'm not familiar with Common-Lisp itself I will leave you with one example and a link.
(defun flatten (structure)
(cond ((null structure) nil)
((atom structure) (list structure))
(t (mapcan #'flatten structure))))
Flatten a list - Rosetta Code
flatten takes an arbitrary s-expression like a nested list '(1 (2 3) 4) and returns '(1 2 3 4).
So now you just have to write a new function in which you use your printelems as a helper function and give it flattened lists.
(defun printelems.v2 (L1 L2)
(printelems (flatten L1) (flatten L2)))
Take this with a grain of salt, since as said before I'm not familiar with Common-Lisp, so appologies in advance for any potential syntax errors.

Scheme: Return all elements of an expression that can be obtained using any combination of car and cdr

I'm trying to write a procedure in Scheme (R5RS) of my CS class that takes an expression (either a symbol or a list) as an argument and returns a list of (1) all the possible expression that can be formed by using car and cdr on the expression and (2) and an expression demonstrating how each of these components of the original expression were obtained. If a piece can be obtained in more than one way, it should be returned more than once.
Examples
(pieces '()) => ((() x))
(pieces 'apple) => ((apple x))
(pieces '(apple)) => (((apple) x) (apple (car x)) (() (cdr x)))
(pieces '(a (b c))) =>
(((a (b c)) x)
(a (car x))
(((b c)) (cdr x))
((b c) (car (cdr x)))
(b (car (car (cdr x))))
((c) (cdr (car (cdr x))))
(c (car (cdr (car (cdr x)))))
(() (cdr (cdr (car (cdr x)))))
(() (cdr (cdr x))))
Since we've just started with Scheme, we're limited to fairly basic syntax for this assignment. Here's what I have so far:
(define pieces
(lambda (exp)
(cond
((symbol? exp)
(list exp 'x))
((null? exp)
(list '() 'x))
((list? exp)
(let ((b (pieces (car exp))) (c (pieces (cdr exp))))
(list exp 'x b c))))))
(pieces '()) => (() x)
(pieces 'apple) => (apple x)
(pieces '(apple)) => ((apple) x (apple x) (() x))
(pieces '(a (b c))) => ((a (b c)) x (a x) (((b c)) x ((b c) x (b x) ((c) x (c x) (() x)))
(() x)))
The procedure returns all of the proper elements, but each recursion causes the components to be nested in an additional list. Is there any way to prevent that?
Also, I have no idea where to start for the second part of the problem (showing how each element was obtained from the original using car and cdr). I've tried a million different approaches, and none of them have even been close to working. If anyone has any hints or suggestions on how to implement that feature, I'd really appreciate it. Thanks a ton.
(pieces 'apple) => (apple x)
But it should be ((apple x)), right? You should get a list where the first and only element is the list (apple x).
The cond clauses that terminate recursion (exp is a symbol or null) return items that should go in the list, while the clause that recurs on car and cdr attempts to create a list of items. As pieces can return both items and lists of items it's kind of hard to make a list of items out of the values that are returned from it: when you do (list exp 'x b c) you don't know if b and c are items that should go into the list or lists of items.
If you make sure that pieces always returns a list of items (e.g. (list (list exp 'x))) it gets a lot easier. When you recur on car and cdr you want to do something like append the lists a and b and add the "current" ((list exp 'x)) item to that list (maybe with cons or something).
For the second part, pieces must know how it got to the current item. You can make pieces take a the "path" to the current item as a (maybe optional) parameter. If the path is a list, then when you call pieces on (car exp) you can add a car symbol to the path you're sending as argument, and for (cdr exp) you can add the symbol cdr. And then you use the path to create something nice to substitute for 'x in (list exp 'x).
I know it's not Scheme, but maybe looking at similar language would help. I did this more to practice myself, so take it with a drip of salt, yet it seems to be doing exactly what you're after:
(defun parse-list (whatever)
(labels ((pieces (expression &optional path)
(cond
((null expression)
`((,path . nil)))
((listp expression)
(append (list
`(,path . ,expression))
(pieces (car expression)
(cons 'car path))
(pieces (cdr expression)
(cons 'cdr path))))
(t `((,path . ,expression))))))
(dolist (output (pieces whatever))
(format t "path ~a => result ~a~&"
(car output) (cdr output)))))
(parse-list '(a (b c)))
Which then produces this output:
path NIL => result (A (B C))
path (CAR) => result A
path (CDR) => result ((B C))
path (CAR CDR) => result (B C)
path (CAR CAR CDR) => result B
path (CDR CAR CDR) => result (C)
path (CAR CDR CAR CDR) => result C
path (CDR CDR CAR CDR) => result NIL
path (CDR CDR) => result NIL
Sorry, I couldn't get SO's code formatting better than this :)