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
// Allocates RWX memory of given size and returns a pointer to it. On failure, // prints out the error and returns NULL. void* alloc_executable_memory(size_tsize){ void* ptr = mmap(0, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (ptr == (void*)-1) { perror("mmap"); returnNULL; } return ptr; }