Created
July 5, 2015 16:57
-
-
Save anonymous/baf155489c75f109f0b0 to your computer and use it in GitHub Desktop.
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
// 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