From e3122519dfa1a0a968a4979660bacf47d3ec326d Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Fri, 27 Nov 2020 15:27:35 -0500 Subject: [PATCH] Do the fibs --- variables/src/main.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/variables/src/main.rs b/variables/src/main.rs index 017442e..8c5df33 100644 --- a/variables/src/main.rs +++ b/variables/src/main.rs @@ -18,11 +18,24 @@ fn main() { match command.as_str() { "tc" => { if command_args.len() < 1 { - println!("ERROR: missing a value to convert"); + eprintln!("ERROR: missing a value to convert"); process::exit(1); } temp_convert(command_args[0].as_str().to_string()) } + "fib" => { + if command_args.len() < 1 { + eprintln!("ERROR: missing a value to fib"); + process::exit(1); + } + let n: u64 = command_args[0] + .parse() + .expect("could not parse value to fib"); + if n >= 40 { + eprintln!("WARN: this might take a while"); + } + fib_n(n) + } "rx" => redefine_x(), "help" | _ => show_help(), } @@ -32,8 +45,9 @@ fn show_help() { println!("Usage: variables [command_args]"); println!(); println!("The value for may be one of:"); - println!(" tc - convert temperatures between Fahrenheit and Celsius"); - println!(" rx - redefine x"); + println!(" fib - generate Nth Fibonacci number"); + println!(" tc - convert temperatures between Fahrenheit and Celsius"); + println!(" rx - redefine x"); println!(); } @@ -59,7 +73,7 @@ fn temp_convert(to_convert: String) { .expect("failed to parse temperature"); println!("{}C", temp_convert_f2c(f)); } else { - println!("What are we supposed to do to {:?}?", to_convert); + eprintln!("ERROR: What are we supposed to do to {:?}?", to_convert); } } @@ -70,3 +84,15 @@ fn temp_convert_c2f(c: f32) -> f32 { fn temp_convert_f2c(f: f32) -> f32 { (f - 32.0) * (5.0 / 9.0) } + +fn fib_n(n: u64) { + println!("{}", fib_up_to(n)); +} + +fn fib_up_to(n: u64) -> u64 { + match n { + 0 => 0, + 1 => 1, + _ => fib_up_to(n - 1) + fib_up_to(n - 2), + } +}