formula
2006-09-21
Introduction
This program transforms a formula from some internal representation into a string representation in infix form. It shows decissions being made based on tags in the data, a useful technique for various tasks, such as symbolic computation and interpretation.
C
OCaml
type formula = Int of int
| Var of string
| Add of formula list
| Sub of formula list
let rec formula_to_string x = match x with
Int x -> string_of_int x
| Var x -> x
| Add xs -> String.concat " + "
(List.map formula_to_string xs)
| Sub xs -> String.concat " - "
(List.map (fun x -> match x with
Int _ | Var _ -> formula_to_string x
| _ -> "(" ^ (formula_to_string x) ^ ")") xs)
let _ = print_endline (formula_to_string
(Sub [Int 5; Add [Int 2; Var "a"; Int 1]; Int 1]))
99 words.
It is possible to write the same program without declaring the formula type explicitly:
let rec formula_to_string x = match x with
`Int x -> string_of_int x
| `Var x -> x
| `Add xs -> String.concat " + "
(List.map formula_to_string xs)
| `Sub xs -> String.concat " - "
(List.map (fun x -> match x with
`Int _ | `Var _ -> formula_to_string x
| _ -> "(" ^ (formula_to_string x) ^ ")") xs)
let _ = print_endline (formula_to_string
(`Sub [`Int 5; `Add [`Int 2; `Var "a"; `Int 1]; `Int 1]))
79 words.
Ruby
def formula_to_string x
if x.is_a? Array
if x[0] == :'+'
(x[1..-1].map { |x| formula_to_string x }).join ' + '
else
(x[1..-1].map do |x|
if x.is_a? Array
'(' + formula_to_string(x) + ')'
else
formula_to_string x
end
end).join ' - '
end
else
x.to_s
end
end
puts formula_to_string([:'-', 5, [:'+', 2, :a, 1], 1])
52 words.
Common Lisp
(defun formula-to-string (x)
(if (atom x) (write-to-string x :case :downcase :pretty t)
(case (car x)
(+ (format nil "~{~A~^ + ~}"
(mapcar #'formula-to-string (cdr x))))
(- (format nil "~{~A~^ - ~}"
(mapcar (lambda (y)
(if (atom y) (formula-to-string y)
(concatenate 'string "("
(formula-to-string y)
")")))
(cdr x)))))))
(format t "~A~%" (formula-to-string '(- 5 (+ 2 a 1) 1)))
58 words.