Skip to content

Commit 59b665d

Browse files
committed
forth: add to track
1 parent b326840 commit 59b665d

9 files changed

Lines changed: 686 additions & 0 deletions

File tree

‎config.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -768,6 +768,16 @@
768768

769769
]
770770
},
771+
{
772+
"uuid": "f0c0316d-3fb5-455e-952a-91161e7fb298",
773+
"slug": "forth",
774+
"core": false,
775+
"unlocked_by": null,
776+
"difficulty": 9,
777+
"topics": [
778+
779+
]
780+
},
771781
{
772782
"uuid": "377fe38b-08ad-4f3a-8118-a43c10f7b9b2",
773783
"slug": "custom-set",
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# {{ .Spec.Name }}
2+
3+
{{ .Spec.Description -}}
4+
{{- with .Hints }}
5+
{{ . }}
6+
{{ end }}
7+
{{- with .TrackInsert }}
8+
{{ . }}
9+
{{ end }}
10+
{{- with .Spec.Credits -}}
11+
## Source
12+
13+
{{ . }}
14+
{{ end }}
15+
## Submitting Incomplete Solutions
16+
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
17+

‎exercises/forth/README.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Forth
2+
3+
Implement an evaluator for a very simple subset of Forth.
4+
5+
[Forth](https://en.wikipedia.org/wiki/Forth_%28programming_language%29)
6+
is a stack-based programming language. Implement a very basic evaluator
7+
for a small subset of Forth.
8+
9+
Your evaluator has to support the following words:
10+
11+
- `+`, `-`, `*`, `/` (integer arithmetic)
12+
- `DUP`, `DROP`, `SWAP`, `OVER` (stack manipulation)
13+
14+
Your evaluator also has to support defining new words using the
15+
customary syntax: `: word-name definition ;`.
16+
17+
To keep things simple the only data type you need to support is signed
18+
integers of at least 16 bits size.
19+
20+
You should use the following rules for the syntax: a number is a
21+
sequence of one or more (ASCII) digits, a word is a sequence of one or
22+
more letters, digits, symbols or punctuation that is not a number.
23+
(Forth probably uses slightly different rules, but this is close
24+
enough.)
25+
26+
Words are case-insensitive.
27+
28+
29+
To run the tests:
30+
31+
```sh
32+
$ gradle test
33+
```
34+
35+
For more detailed info about the Java track see the [help page](http://exercism.io/languages/java).
36+
37+
38+
39+
## Submitting Incomplete Solutions
40+
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
41+

‎exercises/forth/build.gradle‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
apply plugin: "java"
2+
apply plugin: "eclipse"
3+
apply plugin: "idea"
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
testCompile "junit:junit:4.12"
11+
}
12+
13+
test {
14+
testLogging {
15+
exceptionFormat = 'full'
16+
events = ["passed", "failed", "skipped"]
17+
}
18+
}
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import java.util.*;
2+
import java.util.function.UnaryOperator;
3+
4+
class ForthEvaluator {
5+
6+
private static final Map<String, UnaryOperator<Deque<Integer>>> BUILT_IN_OPS
7+
= new HashMap<String, UnaryOperator<Deque<Integer>>>() {{
8+
9+
put("+", values -> {
10+
if (values.size() < 2) {
11+
throw new IllegalArgumentException(
12+
"Addition requires that the stack contain at least 2 values");
13+
}
14+
15+
values.push(values.pop() + values.pop());
16+
return values;
17+
});
18+
19+
put("-", values -> {
20+
if (values.size() < 2) {
21+
throw new IllegalArgumentException(
22+
"Subtraction requires that the stack contain at least 2 values");
23+
}
24+
25+
int topValue = values.pop();
26+
int secondValue = values.pop();
27+
28+
values.push(secondValue - topValue);
29+
return values;
30+
});
31+
32+
put("*", values -> {
33+
if (values.size() < 2) {
34+
throw new IllegalArgumentException(
35+
"Multiplication requires that the stack contain at least 2 values");
36+
}
37+
38+
values.push(values.pop() * values.pop());
39+
return values;
40+
});
41+
42+
put("/", values -> {
43+
if (values.size() < 2) {
44+
throw new IllegalArgumentException(
45+
"Division requires that the stack contain at least 2 values");
46+
}
47+
48+
int topValue = values.pop();
49+
int secondValue = values.pop();
50+
51+
if (topValue == 0) {
52+
throw new IllegalArgumentException("Division by 0 is not allowed");
53+
}
54+
55+
values.push(secondValue / topValue);
56+
return values;
57+
});
58+
59+
put("dup", values -> {
60+
if (values.isEmpty()) {
61+
throw new IllegalArgumentException(
62+
"Duplicating requires that the stack contain at least 1 value");
63+
}
64+
65+
values.push(values.peek());
66+
return values;
67+
});
68+
69+
put("drop", values -> {
70+
if (values.isEmpty()) {
71+
throw new IllegalArgumentException(
72+
"Dropping requires that the stack contain at least 1 value");
73+
}
74+
75+
values.pop();
76+
return values;
77+
});
78+
79+
put("swap", values -> {
80+
if (values.size() < 2) {
81+
throw new IllegalArgumentException(
82+
"Swapping requires that the stack contain at least 2 values");
83+
}
84+
85+
int topValue = values.pop();
86+
int secondValue = values.pop();
87+
values.push(topValue);
88+
values.push(secondValue);
89+
return values;
90+
});
91+
92+
put("over", values -> {
93+
if (values.size() < 2) {
94+
throw new IllegalArgumentException(
95+
"Overing requires that the stack contain at least 2 values");
96+
}
97+
98+
int topValue = values.pop();
99+
int secondValue = values.peek();
100+
values.push(topValue);
101+
values.push(secondValue);
102+
return values;
103+
});
104+
}};
105+
106+
private Deque<Integer> values = new ArrayDeque<>();
107+
108+
private List<Token> tokens = new ArrayList<>();
109+
110+
private Map<String, List<Token>> userOps = new HashMap<>();
111+
112+
List<Integer> evaluateProgram(final List<String> program) {
113+
parse(program);
114+
evaluate();
115+
116+
final List<Integer> result = new ArrayList<>(values);
117+
Collections.reverse(result);
118+
return result;
119+
}
120+
121+
private void parse(final List<String> program) {
122+
program.forEach(string -> tokens.addAll(Token.fromString(string)));
123+
}
124+
125+
private void evaluate() {
126+
while (!tokens.isEmpty()) {
127+
final Token token = tokens.remove(0);
128+
129+
if (token instanceof Token.OpDefToken) {
130+
final Token.OpDefToken opDefToken = (Token.OpDefToken) token;
131+
userOps.put(opDefToken.getNewOp().toLowerCase(), opDefToken.getNewOpDefTokens());
132+
} else if (token instanceof Token.OpToken) {
133+
evaluateOpToken((Token.OpToken) token);
134+
} else if (token instanceof Token.IntToken) {
135+
values.push(((Token.IntToken) token).getRawValue());
136+
}
137+
}
138+
}
139+
140+
private void evaluateOpToken(final Token.OpToken opToken) {
141+
final String op = opToken.getOp();
142+
143+
if (userOps.containsKey(op)) {
144+
final List<Token> replacementOps = userOps.get(op);
145+
Collections.reverse(replacementOps);
146+
replacementOps.forEach(token -> tokens.add(0, token));
147+
} else if (BUILT_IN_OPS.containsKey(op)) {
148+
values = BUILT_IN_OPS.get(op).apply(values);
149+
} else {
150+
throw new IllegalArgumentException("No definition available for operator \"" + op + "\"");
151+
}
152+
}
153+
154+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import java.util.Arrays;
2+
import java.util.Collections;
3+
import java.util.List;
4+
import java.util.stream.Collectors;
5+
6+
class Token {
7+
8+
static class OpDefToken extends Token {
9+
10+
static OpDefToken opDefTokenFromString(final String string) {
11+
final String trimmedLine = string.substring(2, string.length() - 2);
12+
final int newOpEnd = trimmedLine.indexOf(" ");
13+
14+
if (newOpEnd == -1) {
15+
throw new IllegalArgumentException("Incomplete operation definition");
16+
}
17+
18+
final Token newOpToken = Token.fromString(trimmedLine.substring(0, newOpEnd)).get(0);
19+
20+
if (!(newOpToken instanceof OpToken)) {
21+
throw new IllegalArgumentException("Cannot redefine numbers");
22+
}
23+
24+
final List<Token> newOpDefTokens = Token.fromString(trimmedLine.substring(newOpEnd + 1));
25+
return new OpDefToken(((OpToken) newOpToken).getOp(), newOpDefTokens);
26+
}
27+
28+
private final String newOp;
29+
30+
private final List<Token> newOpDefTokens;
31+
32+
private OpDefToken(final String newOp, final List<Token> newOpDefTokens) {
33+
this.newOp = newOp;
34+
this.newOpDefTokens = newOpDefTokens;
35+
}
36+
37+
String getNewOp() {
38+
return newOp;
39+
}
40+
41+
List<Token> getNewOpDefTokens() {
42+
return newOpDefTokens;
43+
}
44+
45+
}
46+
47+
static class OpToken extends Token {
48+
49+
private final String op;
50+
51+
OpToken(final String op) {
52+
this.op = op;
53+
}
54+
55+
String getOp() {
56+
return op;
57+
}
58+
59+
}
60+
61+
static class IntToken extends Token {
62+
63+
private final int rawValue;
64+
65+
IntToken(final int rawValue) {
66+
this.rawValue = rawValue;
67+
}
68+
69+
int getRawValue() {
70+
return rawValue;
71+
}
72+
73+
}
74+
75+
static List<Token> fromString(final String string) {
76+
if (string.startsWith(":")) {
77+
return Collections.singletonList(OpDefToken.opDefTokenFromString(string));
78+
} else if (string.matches("[A-z+/*\\-]+(?:-[A-z+/*\\-]+)*")) {
79+
return Collections.singletonList(new OpToken(string.toLowerCase()));
80+
} else if (string.matches("\\d+")) {
81+
return Collections.singletonList(new IntToken(Integer.parseInt(string)));
82+
} else {
83+
return Arrays.stream(string.split(" "))
84+
.map(Token::fromString)
85+
.flatMap(List::stream)
86+
.collect(Collectors.toList());
87+
}
88+
}
89+
90+
}

‎exercises/forth/src/main/java/.keep‎

Whitespace-only changes.

0 commit comments

Comments
 (0)