Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contributing translation of js's track 'forth' excersize. #398

Merged
merged 7 commits into from
Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/links.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ name: Links
on:
pull_request:
paths:
- '.github/workflows/links.yml'
# - '.github/workflows/links.yml' Temporarily disabled by @Stargator
- 'concept/**/*.md'
- 'concept/**/links.json'
- 'docs/*.md'
- 'exercises/**/*.md'
# - 'exercises/**/*.md' Temporarily disabled by @Stargator
- 'reference/*.md'
- '*.md'
- '**/**/*.md'
Expand Down
9 changes: 9 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,15 @@
"math"
]
},
{
"slug": "forth",
"name": "Forth",
"uuid": "7137cdad-fdac-4e30-836a-c92c352bdc4d",
"practices": [],
"prerequisites": [],
"difficulty": 8,
"topics": ["domain_specific_languages", "parsing", "stacks"]
},
{
"slug": "word-count",
"name": "Word Count",
Expand Down
22 changes: 22 additions & 0 deletions exercises/practice/forth/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Instructions

Implement an evaluator for a very simple subset of Forth.

[Forth] is a stack-based programming language.
Implement a very basic evaluator for a small subset of Forth.

Your evaluator has to support the following words:

- `+`, `-`, `*`, `/` (integer arithmetic)
- `DUP`, `DROP`, `SWAP`, `OVER` (stack manipulation)

Your evaluator also has to support defining new words using the customary syntax: `: word-name definition ;`.

To keep things simple the only data type you need to support is signed integers of at least 16 bits size.

You should use the following rules for the syntax: a number is a sequence of one or more (ASCII) digits, a word is a sequence of one or more letters, digits, symbols or punctuation that is not a number.
(Forth probably uses slightly different rules, but this is close enough.)

Words are case-insensitive.

[Forth]: https://en.wikipedia.org/wiki/Forth_(programming_language)
22 changes: 22 additions & 0 deletions exercises/practice/forth/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"blurb": "Implement an evaluator for a very simple subset of Forth.",
"authors": [
"matthewmorgan"
],
"contributors": [
"AlexeyBukin"
],
"files": {
"solution": [
"lib/forth.dart"
],
"test": [
"test/forth_test.dart"
],
"example": [
".meta/lib/example.dart"
]
},
"source": "Exercism JS track",
"source_url": "https://exercism.org/tracks/javascript/exercises/forth"
}
150 changes: 150 additions & 0 deletions exercises/practice/forth/.meta/lib/example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import 'dart:collection';

class Forth {
final _stack = _Stack();

List<int> get stack => _stack.asList;

late final flattenDictionary = <String, String>{};

late final evaluateDictionary = <String, void Function()>{
'+': addition,
'-': subtraction,
'*': multiplication,
'/': division,
'dup': dup,
'drop': drop,
'swap': swap,
'over': over,
};

void evaluate(String expression) {
final flat = flatten(expression.toLowerCase());

if (flat.isEmpty) {
return;
}
final words = flat.split(' ');
for (final word in words) {
if (evaluateDictionary.containsKey(word)) {
evaluateDictionary[word]!.call();
} else {
final number = int.parse(word);
_stack.push(number);
}
}
}

String flatten(String expression) {
final words = expression.split(' ');
for (int t = 0; t < words.length; t++) {
final word = words[t];
if (flattenDictionary.containsKey(word)) {
words[t] = flattenDictionary[word]!;
} else if (word == ':') {
final semicolon = words.indexOf(';', t);
if (semicolon == -1) {
throw Exception('Unterminated definition');
}
defineCommand(words[t + 1], words.sublist(t + 2, semicolon).join(' '));
words.removeRange(t, semicolon + 1);
t = semicolon;
} else if (!evaluateDictionary.containsKey(word) && !isKeyword(word)) {
throw Exception('Unknown command');
}
}
return words.join(' ');
}

/// Must be not a number (-?\d+), not a ':', not a ';'
static bool isKeyword(String word) => RegExp(r'^(-?\d+|:|;)$').hasMatch(word);

void defineCommand(String word, String expression) {
if (isKeyword(word)) {
throw Exception('Invalid definition');
}
flattenDictionary[word] = flatten(expression);
}

void addition() {
final a = _stack.pop();
final b = _stack.pop();
_stack.push(b + a);
}

void subtraction() {
final a = _stack.pop();
final b = _stack.pop();
_stack.push(b - a);
}

void multiplication() {
final a = _stack.pop();
final b = _stack.pop();
_stack.push(b * a);
}

void division() {
final a = _stack.pop();
if (a == 0) {
throw Exception('Division by zero');
}
final b = _stack.pop();
_stack.push(b ~/ a);
}

void dup() {
final a = _stack.peek();
_stack.push(a);
}

void drop() {
_stack.pop();
}

void swap() {
final a = _stack.pop();
final b = _stack.pop();
_stack.push(a);
_stack.push(b);
}

void over() {
final a = _stack.pop();
final b = _stack.peek();
_stack.push(a);
_stack.push(b);
}
}

class _Stack {
List<int> get asList => _stack.toList();

final _stack = Queue<int>();

bool get isEmpty => _stack.isEmpty;

int get size => _stack.length;

int peek() {
if (_stack.isEmpty) {
throw Exception('Stack empty');
}
return _stack.last;
}

int pop() {
if (_stack.isEmpty) {
throw Exception('Stack empty');
}
return _stack.removeLast();
}

void push(int number) {
_stack.addLast(number);
}

void deleteAll({int after = 0}) {
_stack.take(after);
}
}
18 changes: 18 additions & 0 deletions exercises/practice/forth/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
errors:
unused_element: error
unused_import: error
unused_local_variable: error
dead_code: error

linter:
rules:
# Error Rules
- avoid_relative_lib_imports
- avoid_types_as_parameter_names
- literal_only_boolean_expressions
- no_adjacent_strings_in_list
- valid_regexps
3 changes: 3 additions & 0 deletions exercises/practice/forth/lib/forth.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class Forth {
// Put your code here
}
5 changes: 5 additions & 0 deletions exercises/practice/forth/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: 'forth'
environment:
sdk: '>=2.12.0 <3.0.0'
dev_dependencies:
test: '<2.0.0'
Loading