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