Skip to content

Instantly share code, notes, and snippets.

Created July 5, 2015 16:57
Show Gist options
  • Save anonymous/baf155489c75f109f0b0 to your computer and use it in GitHub Desktop.
Save anonymous/baf155489c75f109f0b0 to your computer and use it in GitHub Desktop.
// Directives
#![allow(unused_must_use)]
// Imports
use std::slice::Iter;
use std::iter::Peekable;
/// Takes a string of chars and returns a vector of tokens.
fn tokenize(chars:&str) -> Vec<String> {
chars.replace("(", " ( ")
.replace(")", " ) ")
.split_whitespace()
.filter(|s| !(s.is_empty()))
.map(|s| s.to_string())
.collect()
}
/// Reads an expression from a sequence of tokens.
fn read_from_tokens(tokens: &mut Peekable<Iter<String>>) -> Data {
if tokens.len() == 0 {
panic!("Unexpected EOF while parsing.");
}
let token = tokens.next().unwrap();
if token == "(" {
let mut l = Nil;
while *tokens.peek().expect("Syntax error! Expected ')'") != ")" {
l = read_from_tokens(tokens).cons(l);
}
tokens.next();
return l.nreverse();
}
match token.parse::<f32>() {
Ok(f) => return Float(f),
_ => {;}
}
return Symbol(token.to_string())
}
fn parse(program:&str) -> Data {
return read_from_tokens(&mut tokenize(program).iter().peekable());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment