Skip to content

Instantly share code, notes, and snippets.

@amidvidy
Last active January 4, 2016 01:39
Show Gist options
  • Save amidvidy/8549671 to your computer and use it in GitHub Desktop.
Save amidvidy/8549671 to your computer and use it in GitHub Desktop.
my first rust program: a really crappy todo list
use std::io::buffered::BufferedReader;
use std::io;
#[deriving(Clone)]
struct Todo {
desc: ~str,
completed: bool
}
impl Todo {
fn new(desc: ~str) -> Todo {
Todo {desc: desc, completed: false}
}
fn completed(&self) -> Todo {
Todo {desc: self.desc.clone(), completed: true}
}
}
struct TodoList {
todos: ~[Todo]
}
impl TodoList {
fn new() -> TodoList {
TodoList {todos: ~[]}
}
fn add(&self, todo: Todo) -> TodoList {
TodoList {todos: std::vec::append_one(self.todos.clone(), todo)}
}
fn complete(&self, idx: uint) -> TodoList {
let mut ntodos = self.todos.clone();
ntodos[idx] = ntodos[idx].completed();
TodoList {todos: ntodos}
}
fn clear(&self) -> TodoList {
let (_, uncompleted) = self.todos.partitioned({|todo| todo.completed});
TodoList {todos: uncompleted}
}
fn display(&self) {
for (i, todo) in self.todos.iter().enumerate() {
println!("{}.\t{:?}", i, todo);
}
}
}
struct AddOp;
struct CompleteOp;
struct ClearOp;
impl AddOp {
fn execute(todos: &TodoList, desc: &str) -> TodoList {
todos.add(Todo::new(desc.into_owned()))
}
}
impl CompleteOp {
fn execute(todos: &TodoList, idx: uint) -> TodoList {
todos.complete(idx)
}
}
impl ClearOp {
fn execute(todos: &TodoList) -> TodoList {
todos.clear()
}
}
fn main() {
let mut todos = TodoList::new();
let mut reader = BufferedReader::new(io::stdin());
println!("Welcome to the Todo List!");
loop {
println!("Current Items:");
todos.display();
println!("What would you like to do?");
println!("\tADD <desc>\t\tAdd new todo item");
println!("\tCOMPLETE <index>\tMark selected item completed");
println!("\tCLEAR\t\t\tRemove completed items");
println!("\tEXIT\t\t\tExit the program")
// TODO: figure out how to print command prompt
let input = reader.read_line().unwrap_or(~"nothing");
todos = match input.split(' ').nth(0) {
Some("ADD") => AddOp::execute(&todos, input.slice(4, input.len() - 1)),
Some("COMPLETE") => CompleteOp::execute(&todos, from_str::<uint>(input.slice(9,10)).unwrap_or(0)),
Some("CLEAR") => ClearOp::execute(&todos),
Some("EXIT") => break,
_ => todos
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment