Skip to content

Instantly share code, notes, and snippets.

@creationix
Created February 8, 2017 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationix/b4f1084643e3b2fe0bc05efa6a504c56 to your computer and use it in GitHub Desktop.
Save creationix/b4f1084643e3b2fe0bc05efa6a504c56 to your computer and use it in GitHub Desktop.
#[derive(Debug)]
enum Value {
Nil,
Integer(i64),
String(usize),
Pair(usize)
}
#[derive(Debug)]
struct State {
strings: Vec<Option<String>>,
pairs: Vec<Option<(Value, Value)>>
}
impl State {
fn new_string(&mut self, val: String) -> Value {
let entry = Some(val);
for i in 0..self.strings.len() {
if self.strings[i].is_none() {
self.strings[i] = entry;
return Value::String(i);
}
}
self.strings.push(entry);
Value::String(self.strings.len() - 1)
}
fn new_pair(&mut self, left: Value, right: Value) -> Value {
let entry = Some((left, right));
for i in 0..self.pairs.len() {
if self.pairs[i].is_none() {
self.pairs[i] = entry;
return Value::Pair(i);
}
}
self.pairs.push(entry);
Value::String(self.pairs.len() - 1)
}
}
fn main() {
let mut state = State {
strings: Vec::new(),
pairs: Vec::new()
};
println!("A new string: {:?}", state.new_string(String::from("Hello World")));
let mut next = Value::Nil;
for i in 0..10 {
next = state.new_pair(Value::Integer(10 - i), next);
println!("A new pair: {:?}", next);
}
println!("{:?} {:?}", Value::String(0), state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment