Skip to content

Instantly share code, notes, and snippets.

@niconii
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save niconii/4b4dbb3d66e52690eabc to your computer and use it in GitHub Desktop.

Select an option

Save niconii/4b4dbb3d66e52690eabc to your computer and use it in GitHub Desktop.
Awful Result/try! implementation in C
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
enum ResultKind { Kind_Ok, Kind_Err };
typedef struct {
enum ResultKind kind;
union {
struct { int ok; };
struct { char* err; };
};
} ResultInt;
bool is_ok(ResultInt* r) {
return (r->kind == Kind_Ok);
}
bool is_err(ResultInt* r) {
return (r->kind == Kind_Err);
}
int get_ok(ResultInt* r) {
assert(is_ok(r));
return r->ok;
}
char* get_err(ResultInt* r) {
assert(is_err(r));
return r->err;
}
void print_result(ResultInt* r) {
if (is_ok(r)) {
printf("Ok(%i)\n", get_ok(r));
} else {
printf("Err(\"%s\")\n", get_err(r));
}
}
ResultInt Ok(int ok) {
ResultInt out;
out.kind = Kind_Ok;
out.ok = ok;
return out;
}
ResultInt Err(char* err) {
ResultInt out;
out.kind = Kind_Err;
out.err = err;
return out;
}
#define TRY(var, r) {\
if (is_ok(r)) {\
*var = get_ok(r);\
} else {\
return *r;\
}\
}
/* user code below */
ResultInt ensure_positive(int input) {
if (input >= 0) {
return Ok(input);
} else {
return Err("input was negative!");
}
}
ResultInt mul_naturals(int a, int b) {
int x, y;
ResultInt result;
result = ensure_positive(a);
TRY(&x, &result);
result = ensure_positive(b);
TRY(&y, &result);
return Ok(x * y);
}
int main() {
ResultInt result;
result = mul_naturals(2, 3);
print_result(&result);
result = mul_naturals(5, -6);
print_result(&result);
return 0;
}
Ok(6)
Err("input was negative!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment