Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Common Lisp

Name: Shortest Function Wins 2009-11-13 13:53

I will post my implementation in a couple days. May the best EXPERT PROGRAMMER win

Write the function
simplify (x)
returns an expression in which constants have been combined and unnecessary operators have been
removed. x is a valid arithmetic LISP expression involving only the operators "+" and "*". Examples:
Expression Returns
(simplify ’a) a
(simplify ’(*)) 1
(simplify ’(+ a)) a
(simplify ’(* 1 a 1 1 1)) a
(simplify ’(* 8 7)) 56
(simplify ’(* 3 0 4)) 0
(simplify ’(+ a 1 2 b)) (+ 3 a b)
(simplify ’(* 4 (+ 2 3) (+ 1 2 3) (* 2 3))) 720
(simplify ’(+ 4 (+ 2 3 b) (+ 1 2 c 3) (* 2 3))) (+ 10 (+ 5 b) (+ 6 c))
(simplify ’(* 4 (+ 2 3 b) (+ 1 2 c 3) (* 2 3))) (* 24 (+ 5 b) (+ 6 c))
Note how constants are combined or eliminated whenever possible, and how the simplifications apply
recursively. Also note that adjacent unsimplifiable expressions are not combined; e.g., in the second to
last expression, the "+" operators are not combined to
(+ 21 b c)
That form of simplification is beyond this program. See the correct output for more examples.
Part 4:

Name: CL is pig disgusting 2009-11-13 17:10

(define (simplify x)
  (if (pair? x)
      (do ((n '()) (r '()) (l (map simplify (cdr x)) (cdr l)))
        ((null? l)
         (let* ((r (reverse r))
                (p (eq? (car x) '*))
                (n (apply (if p * +) n))
                (u (= (length r) 1)))
           (if (null? r) n
           (if (= n 0) (if p 0 (if u (car r) (cons '+ r)))
           (if (and p (= n 1)) (if u (car r) (cons '* r))
               (cons (car x) (cons n r)))))))
        (if (number? (car l))
            (set! n (cons (car l) n))
            (set! r (cons (car l) r))))
      x))


55 paren pairs, but 2 don't really count because they're quoted. (37 with partition from SRFI 1 and receive from SRFI 8)

>>6
Yes, CL and Scheme are obviously too inflexible to add a pattern matcher.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List