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:
Easy stuff. The last time I did a program like this I refused to skimp on simplification, derivation, or integration.
Do you know how hellish it is to integrate this shit?
Name:
Anonymous2009-11-13 14:23
I wanted to write this in Haskell but then I realized it isn't homoiconic :(
Does some variant of Lisp have pattern matching?
>>10
I wasn't implying that they were too inflexible, but I had presumed he wanted pattern matching built-in and not as a library.
Name:
Anonymous2009-11-13 17:29
OP Here, forgot to mention the stuff to the right of the calls is sample output.
Also
NO ITERATION, NO DESTRUCTIVE CALLS
SOLUTION MUST BE RECURSIVE OR USE FUNCTION MAPPING
Name:
Anonymous2009-11-13 17:40
>>10
My god, what an ugly language!
Here's my CL-NOOB implomontation.
(defun simplify (l)
(if (consp l)
(let* ((o (car l))
(a (mapcar #'simplify (cdr l)))
(m (remove-if-not #'numberp a))
(s (remove-if #'numberp a))
(n (apply o m)))
(cond ((null s) n)
((not (or (and (eq o '+) (= n 0))
(and (eq o '*) (= n 1))))
(list* o n s))
((cdr s)
(list* o s))
(t (car s))))
l))
;; it's been so long since I got to do someone's homework
Name:
Anonymous2009-11-13 17:46
>>12
Oh, fuck yoy!!! I'm posting this shit anyway. Next time state all requirements from the start, fucko.
(defun simplify (expr)
(if (atom expr)
expr
(loop for i in (cdr expr)
for si = (simplify i)
when (numberp si) collect si into numbers
when (not (numberp si)) collect si into not-numbers
finally
(return (let ((result (apply (car expr) numbers)))
(if (null not-numbers)
result
(cons (car expr) (cons result not-numbers))))))))
>>16 (if (= (length others) 1)
others
(cons operator-symbol others))
That should be (car others), and the two conds could be simplified into one
Name:
Anonymous2009-11-14 0:25
Here's a more ENTERPRISE aproach to it:
;;; or just make an asdf proj for this
(eval-when (:compile-toplevel :load-toplevel :execute)
(asdf:oos 'asdf:load-op '#:arnesi))