An S-expression is a way of writing a nested list or tree of data, which you may recognize from their use in Lisp, which uses them for source code.
An S-expression is made up of atoms, in this challenge represented by single characters, and expressions, which are written enclosed in parentheses as an atom followed by one or more S-expressions. For example, *
and 2
are atoms, and (* 2)
is an expression. Similarly, (* (* 2) 2)
is also an expression; these can be deeply nested.
Note that ((* 2) 2)
is not a valid expression, since its first item is not an atom. This makes the structure distinct from an arbitrary binary tree. As such, your program will not need to handle such input.
Your task is to, given an S-expression, output an ASCII-art diagram representing it.
The diagram is made of diagonal lines of backslashes with forward slashes poking out at every child of the expression. If the child is an atom, it comes directly after the line coming out. If it is an expression, a new line is drawn starting at that point.
The following examples should make the description clearer.
Given the input (* 2 (+ 3 4))
:
/\
* /\
2 /
/\
+ /\
3 /
4
Given (* (+ 3 4) 2)
:
/\
* /\
/\ \
+ /\ \
3 / /
4 2
Given (+ (+ (+ 1 2) 3) 4)
:
/\
+ /\
/\ \
+ /\ \
/\ \ \
+ /\ \ \
1 / / /
2 3 4
Given (+ 1 (* 2) 3 (- (+ 4 (- 5) 6) (+ 7)) 8)
:
/\
+ /\
1 /\
/\ \
* / /\
2 3 /\
/\ \
- /\ \
/\ \ \
+ /\ \ \
4 /\ \ \
/\ \ \ \
- / / / \
5 6 /\ /
+ / 8
7
Given (+ (+ (+ (+ (+ 1)))) 2)
:
/\
+ /\
/\ \
+ / \
/\ \
+ / \
/\ /
+ / 2
/\
+ /
1
You can take the input in any parsed form, e.g. ['*', ['+', '3', '4'], '2']
.
The atoms in the expression will be single characters, printable ASCII, and not \
or /
.