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: Anonymous 2009-11-13 18:31

Since no-one has posted a PIG DISGUSTING solution yet, I shall post one

(require srfi/1)

(define (simplify exp)
  (if (pair? exp)
      (let* ((operator-symbol (car exp))
             (operator (eval operator-symbol))
             (args (cdr exp))
             (simplified-args (map simplify args)))
        (case (length simplified-args)
          ((0) (apply operator '()))
          ((1) (car simplified-args))
          (else
           (let-values (((numbers others) (partition number? (map simplify simplified-args))))
             (cond ((= (length numbers) 0)
                    (cons operator-symbol others))
                   ((= (length others) 0)
                    (apply operator numbers))
                   (else
                    (let ((total (apply operator numbers)))
                      (cond ((= total 0)
                             (if (eq? operator-symbol '+)
                                 (if (= (length others) 1)
                                     others
                                     (cons operator-symbol others))
                                 0))
                            ((and (= total 1) (eq? operator-symbol '*))
                             (if (= (length others) 1)
                                 (car others)
                                 (cons operator-symbol others)))
                            (else
                             (cons operator-symbol
                                   (cons total others)))))))))))
          exp))


If you read that and your eyes didn't bleed I feel sorry for you

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