Last active
March 27, 2020 03:31
-
-
Save s5bug/ac7aa1350786a117ccb508f34d8b8619 to your computer and use it in GitHub Desktop.
Zig Monad Experiments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn main() void { | |
const my_monadic_result: u64 = my_monadic_program(Id, MonadId); | |
std.debug.warn("{}", .{ my_monadic_result }); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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