Created
August 30, 2019 17:33
-
-
Save kmizu/a6c6202b3aa2684cccff6d94b4cde83e to your computer and use it in GitHub Desktop.
define List Monad for java.util.List
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
import java.util.*; | |
import java.util.stream.*; | |
import java.util.function.*; | |
public class Monadic { | |
// define List Monad | |
public static class ListMonad<T> { | |
public List<T> unit(T x) { | |
return List.of(x); | |
} | |
public <U> List<U> bind(List<T> xs, Function<T, List<U>> fun) { | |
return xs.stream().flatMap(x -> fun.apply(x).stream()).collect(Collectors.toList()); | |
} | |
} | |
public static void main(String[] args) { | |
//create List Monad | |
var listMonad = new ListMonad<Integer>(); | |
// use List Monad | |
// for { x <- List(1, 2, 3) | |
// y <- List(4, 5, 6) } yield (x + y) | |
var result1 = listMonad.bind( | |
List.of(1, 2, 3), | |
x -> listMonad.bind( | |
List.of(4, 5, 6), | |
y -> listMonad.unit(x + y) | |
) | |
); | |
System.out.println(result1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment