Skip to content

Instantly share code, notes, and snippets.

View zarinfam's full-sized avatar

Saeed Zarinfam zarinfam

View GitHub Profile
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:24
Created with Copy to Gist
var p = new Person("Saeed", "[email protected]");
var json = toJson(p, personWriter()).as(JsObject.class);
System.out.println(json.get().get("name").as(JsString.class).get());
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:22
Created with Copy to Gist
static <A> Json toJson(A value, JsonWriter<A> w){
return w.write(value);
}
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:21
Created with Copy to Gist
static JsonWriter<Person> personWriter() {
return v -> new JsObject(Map.of("name", new JsString(v.getName()), "email", new JsString(v.getEmail())));
}
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:20
Created with Copy to Gist
class Person {
private String name;
private String email;
public Person(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:19
Created with Copy to Gist
interface JsonWriter<A> {
Json write(A value);
static JsonWriter<String> stringWriter() {
return JsString::new;
}
}
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:18
Created with Copy to Gist
interface Json{
default <T> T as(){
return (T) this;
}
default <T> T as(Class<T> clazz){
return clazz.cast(this);
}
}
class JsObject implements Json{
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:16
Created with Copy to Gist
var pairs = List.of(new Pair<>(1, "hello"), new Pair<>(2, " "), new Pair<>(3, "world"));
System.out.println(show(combineAll(pairs, deriveMonoidPair(intAdditionMonoid(), stringConcatMonoid())), showPair(showInt(), showString())));
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:14
Created with Copy to Gist
interface Monoid<A> extends Empty<A> {
A combine(A x, A y);
...
static <A, B> Monoid<Pair<A, B>> deriveMonoidPair(Monoid<A> A, Monoid<B> B) {
return new Monoid<>() {
@Override
public Pair<A, B> combine(Pair<A, B> x, Pair<A, B> y) {
return new Pair<>(A.combine(x.getFirst(), y.getFirst()), B.combine(x.getSecond(), y.getSecond()));
@zarinfam
zarinfam / gist.java
Created June 25, 2019 09:13
Created with Copy to Gist
class Pair<A, B> {
private A first;
private B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
@zarinfam
zarinfam / gist.java
Last active June 25, 2019 09:12
Created with Copy to Gist
var mPairs = List.of(
new MPair<>(1, "hello", intAdditionMonoid(), stringConcatMonoid())
, new MPair<>(2, " ", intAdditionMonoid(), stringConcatMonoid())
, new MPair<>(3, "world", intAdditionMonoid(), stringConcatMonoid()));
combineAll(mPairs)
.ifPresent(v -> System.out.println(show(v, showMPair(showInt(), showString()))));