printf(ANSI_COLOR_RED "This text is RED!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_GREEN "This text is GREEN!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_YELLOW "This text is YELLOW!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_BLUE "This text is BLUE!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_CYAN "This text is CYAN!" ANSI_COLOR_RESET "\n"); return0; }
這方法簡單,不過麻煩的是要手動加上Color跟Reset標籤在文字前後。
C++11 Solution
突然想到可以用C++11的新特性User defined literal來簡化,可以減少不少手動置入的風險。也可以練習User defined literal的如何使用。
macro_rules! min { // base case ($x:expr) => ($x); // `$x` followed by at least one `$y,` ($x:expr, $($y:expr),+) => ( // call min! on the tail `$y` std::cmp::min($x, min!($($y),+)) ) }
intg(int x){ if (x == 0) throwstd::exception("cannot be zero in g"); return100 / x + 1; } intf(int x) { int v1 = g(x); if (v1 == 0) throwstd::exception("cannot be zero in f"); return100 / v1; } try { f(0); } catch (std::exception e) { }
enumResult { Value(i32), Error(&'staticstr) } fndiv(x: Result, y: Result) -> Result { match y { Result::Value(0) => Result::Error("Cannot divide 0"), Result::Value(y_) => { match x { Result::Value(x_) => Result::Value(x_ / y_), _ => x } }, _ => y } } fnadd1(x: Result) -> Result { match x { Result::Value(v) => Result::Value(v + 1), _ => x } } fnf(x: i32) -> Result { return div(Result::Value(100), add1(div(Result::Value(100), Result::Value(x)))); } fnmain() { let value = f(25); match value { Result::Value(v) => println!("The result value is {}", v), Result::Error(str) => println!("Error happen, {}", str) } }
座個事情很簡單,如果Result是有效的值就繼續往下做,不然就直接往後傳。
Enhance Monad solution for Railway Oriented Programming