Demo entry 2843311

HW5

   

Submitted by Vankhanh Dinh on Oct 20, 2015 at 08:17
Language: Common Lisp. Code size: 2.0 kB.

(defun linearp (A)
  ; Don't need to check for (null A) because (atom NIL) => t
  ; (cond ((atom A) t)
  ;       ((atom (car A)) (linearp (cdr A)))))
  (or (atom A) ; They're just booleans.
     (reduce (lambda (y z) (and y z)) (mapcar (lambda (x) (atom x)) A)))) ; figure out if something is not an atom.

(defun test-linearp ()
  (print (linearp NIL))
  (print (linearp 'A))
  (print (linearp '(A B C D)))
  (print (linearp '(A B (B C) D)))
  (print (linearp '((A B) C D)))
  (print (linearp '(((A)))))
  (print (linearp '(A (B) ((C)) (((D))))))
  t)

(defun mirror (B)
  ; If it is an atom, just return it
  ; Else, map over the list. If an element is a list, recurse into it.
  ; After that, reverse each list.
  (if (atom B)
      B
      (reverse (mapcar (lambda (x) (if (atom x) x (mirror x))) B))))

(defun test-mirror ()
  (print (mirror 'A)) ; => 'A
  (print (mirror '(A))) ; => '(A)
  (print (mirror '(D C B A))) ; => '(A B C D)
  (print (mirror '((((D C B A)))) )) ; => '((((A B C D))))
  (print (mirror '((D C) (B A)) )) ; => '((A B) (C D))
  (print (mirror '(((E D) C) (B A)) )) ; => '((A B) (C (D E)))
  (print (mirror '(D (C) ((B)) (((A)))) )) ; => '((((A))) ((B)) (C) D)
  (print (mirror '(((((G F) E) D) C) ((B (A)))) )) ; => '((((A) B)) (C (D (E (F G)))))
  (print (mirror '(A (C B)))) ; => '((B C) A)
  t)


(defun replace (S1 S2 S3)
  ; Functionally equivalent
  ; (cond ((and (atom S1) (equal S1 S2)) S2)
  ;	((null S1) NIL)
  ;	((equal (car S1) S2) (cons S3 (replace (cdr S1) S2 S3)))
  ;	(t (cons (car S1) (replace (cdr S1) S2 S3)))))
  ; If an element is equal to S2, replace with S3.
   (mapcar (lambda (x) (if (equal x S2) S3 x)) S1))

(defun test-replace ()
  (print (replace '(A (B C) D) '(B C) 'Y))
  (print (replace '(A (B C) D) 'B 'Y))
  (print (replace '(((B C)) A D) '((B C)) '(EGGS CHEESE)))
  (print (replace '(A B A C A D) 'A '(Do the alphabet)))
  (print (replace '(A B (A B) A B) 'A 'B))
  (print (replace '(today is a bad day) 'bad 'good))
  t)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).