Created
May 27, 2023 11:03
-
-
Save olexale/ee9dbfcc37981a0cbbb9293cd57e84cf to your computer and use it in GitHub Desktop.
scheme dart 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Future<void> main() async { | |
// final program = '(define x 42)'; | |
final program = '(begin (define circle-area (lambda (r) (* pi (* r r)))) (circle-area 10))'; | |
print(parse(program)); | |
} | |
dynamic parse(String program) => parseTokens(tokenize(program)); | |
List<String> tokenize(String program) => program | |
.replaceAll('(', ' ( ') | |
.replaceAll(')', ' ) ') | |
.split(' ') | |
.where((token) => token.isNotEmpty) | |
.toList(); | |
dynamic parseTokens(List<String> tokens) { | |
if (tokens.isEmpty) { | |
throw Exception('Unexpected EOF'); | |
} | |
final token = tokens.removeAt(0); | |
if (token == '(') { | |
final elements = <dynamic>[]; | |
while (tokens.first != ')') { | |
elements.add(parseTokens(tokens)); | |
if (tokens.isEmpty) { | |
throw Exception('Unexpected EOF'); | |
} | |
} | |
tokens.removeAt(0); // remove ')' | |
return elements; | |
} else if (token == ')') { | |
throw Exception('Unexpected ")"'); | |
} else { | |
return _atom(token); | |
} | |
} | |
dynamic _atom(String token) { | |
// parse doubles | |
final d = double.tryParse(token); | |
if (d != null) { | |
return d; | |
} | |
// parse booleans | |
if (token == '#t') { | |
return true; | |
} | |
if (token == '#f') { | |
return false; | |
} | |
// parse strings | |
if (token.startsWith('"') && token.endsWith('"')) { | |
return token.substring(1, token.length - 1); | |
} | |
return Symbol(token); | |
} | |
class Symbol { | |
const Symbol(this.name); | |
final String name; | |
@override | |
String toString() => name; | |
@override | |
bool operator ==(Object other) => | |
identical(this, other) || | |
other is Symbol && runtimeType == other.runtimeType && name == other.name; | |
@override | |
int get hashCode => name.hashCode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment