Created
January 12, 2020 18:50
-
-
Save tyler569/39bc5aadaec236108d4666b754d17b84 to your computer and use it in GitHub Desktop.
Revisions
-
tyler569 created this gist
Jan 12, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,69 @@ import java.util.function.*; interface Monad<T> { Monad<T> bind(Function<T, Monad<T>> fn); } class maybe<T> implements Monad<T> { boolean valid; T value; maybe(boolean v, T val) { valid = v; value = val; } maybe() { valid = false; value = null; } public Monad<T> bind(Function<T, Monad<T>> fn) { if (valid) { return fn.apply(value); } else { return None(); } } public static <U> maybe<U> Just(U value) { return new maybe<U>(true, value); } public static <U> maybe<U> None() { return new maybe<U>(); } public String toString() { if (valid) { return "Some(" + value.toString() + ")"; } else { return "None()"; } } } public class monad { static maybe<Integer> incEven(Integer j) { if (j % 2 == 0) { return maybe.None(); } else { return maybe.Just(j + 1); } } static maybe<Integer> half(Integer j) { return maybe.Just(j / 2); } public static void main(String[] args) { for (int i=0; i<20; i++) { Monad<Integer> some = maybe.Just(i); Monad<Integer> g = some.bind((j) -> incEven(j)); Monad<Integer> h = g.bind((j) -> half(j)); Monad<Integer> k = h.bind((j) -> incEven(j)); System.out.println(k); } } }