Saturday, April 2, 2016

Atoms and Tokens

The atomic score (or a.s., as abbreviated further in this post) of a program is the number of functional tokens in the program. Sometimes, the atomic score does not take into count separators such as parentheses and semicolons, in some languages. However, it is not immediately clear as to how many of these there are in a program.

I found a neat rule-of-thumb technique for calculating the a.s. of a JavaScript program, and any other line-independent program: put the smallest amount of code you can en each line without changing the program (i.e., without causing a syntax error). Let's look at the following program:
var userInput = Number(Prompt("Give me some input!!"));
userInput += 20;
alert("Your number plus twenty: " + userInput);
userInput >>= 1;
alert(userInput);
Let's line-ify this! We'll remove what whitespace we can in the process.
var
userInput
=
Number
(
Prompt
(
"Give me some input!!"
)
)
;
userInput
+=
20
;
alert
(
"Your number plus twenty: "
+
userInput
)
;
userInput
>>=
1
;
alert
(
userInput
)
;
This is 31 lines, or roughly 31 tokens. If we remove separators (parens etc.) and remove non-significant tokens (e.g. var and the trailing semicolon), this becomes 21 tokens:
userInput
=
Number
Prompt
"Give me some input!!"
;
userInput
+=
20
;
alert
"Your number plus twenty: "
+
userInput
;
userInput
>>=
1
;
alert
userInput

Examples

Let's try a some more examples that compare JavaScript, Jolf, a procedural golfing language, and some other various languages. For each task, I will provide a table for each language/language style and its respective a.s. Each program will be golfed to the intent of minimizing the a.s. This means that they will retain whitespace for readability. Each tokenized program will be followed by its a.s.

Task 1: Add two inputs

JavaScript (full program) Tokenized
alert(Number(prompt()) + Number(prompt()));
alert
Number
prompt
+
Number
prompt
a.s. = 5
JavaScript (ES6 arrow function) Tokenized
(a, b) => a + b;
a
,
b
=>
a
+
b
a.s. = 7
Jolf Tokenized
+jJ
+
j
J
a.s. = 3
Japt Tokenized
U+V
U
+
V
a.s. = 3
J, Jelly, APL Tokenized
+
+
a.s. = 1

Task 2: Summation over array

Takes input as [a, b, c, …, z] and outputs a + b + c + … + z.
JavaScript (full program) Tokenized
alert(prompt().split(",").reduce(function(p, c){
    return p + c;
}));
alert
prompt
.
split
","
.
reduce
function
p
,
c
return
p
+
c
a.s. = 15
JavaScript (ES6 arrow function) Tokenized
x => x.reduce((p, c) => p + c);
x
=>
x
.
reduce
p
,
c
=>
p
+
c
a.s. = 11
Jolf Tokenized
ux
u
x
a.s. = 2
Japt Tokenized
UrAB{A+B
U
r
A
B
{
A
+
B
a.s. = 8
J, Jelly, APL Tokenized
+/
+
/
a.s. = 2
Jelly Tokenized
S
S
a.s. = 1

Final remarks

Jelly is wicked short, and it's absolutely fantastic. Japt is beautiful, and I probably did something horribly wrong in my summation attempt. Finally, Jolf is my child, and it will also be first place in my mind.

Also, feel free to correct me if I'm wrong.

No comments:

Post a Comment