Tagged as challenge
Written on 2018-01-31
Write a function random-expression
which generates a random math
expression built up by numbers, +
, unary/binary -
, *
, /
, ^
,
and sqrt
. There should be two outputs: (1) the generated expression
in unevaluated form, and (2) the evaluated answer. Decide on and
explain your choice of arguments to random-expression
to bound the
size of the expression.
Bonus: Write this in both a dynamically typed language and a strictly typed language.
Extend evaluate-expression
to take into account a variable called
operator-table
which contains the operators used in random
generation and their arities. For example, the default table might
look like this in Common Lisp:
(defvar *operator-table*
'((+ 2)
(- 1 2) ; unary and binary -
(* 2)
(/ 2)
(expt 2)
(sqrt 1)))
Feel free to add information to the table as you see fit.