Skip to content

Instantly share code, notes, and snippets.

@s5bug
Last active March 27, 2020 03:31
Show Gist options
  • Save s5bug/ac7aa1350786a117ccb508f34d8b8619 to your computer and use it in GitHub Desktop.
Save s5bug/ac7aa1350786a117ccb508f34d8b8619 to your computer and use it in GitHub Desktop.
Zig Monad Experiments
pub fn Id(comptime A: type) type { return A; }
pub fn identity(comptime A: type, a: A) A { return a; }
pub fn map(comptime A: type, comptime B: type, a: A, f: fn (_: A) B) B {
return f(a);
}
pub const MonadId = Monad(Id, identity, map);
pub fn increment(
comptime M: fn (comptime _: type) type,
monad: Monad(M, _, _)
) (fn (u64) M(u64)) {
const Closure = struct {
fn apply(x: u64) M(u64) {
return monad.pure(x + 1);
}
};
return Closure.apply;
}
pub fn my_monadic_program(
comptime M: fn (comptime _: type) type,
monad: Monad(M, _, _)
) M(u64) {
return monad.flat_map(u64, u64, monad.pure(0), increment(M, monad));
}
pub fn main() void {
const my_monadic_result: u64 = my_monadic_program(Id, MonadId);
std.debug.warn("{}", .{ my_monadic_result });
}
pub fn Monad(
comptime M: fn (comptime _: type) type,
pure0: fn (comptime A: type, _: A) M(A),
flat_map0: fn (comptime A: type, comptime B: type, _: M(A), _: fn (_: A) M(B)) M(B)
) type {
return struct {
pub const pure = pure0;
pub const flat_map = flat_map0;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment