Skip to content

Instantly share code, notes, and snippets.

@jbgi
Created April 20, 2017 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbgi/d6b677d084fafc641fe01f7ffd00591c to your computer and use it in GitHub Desktop.
Save jbgi/d6b677d084fafc641fe01f7ffd00591c to your computer and use it in GitHub Desktop.
import java.io.IOException;
import org.derive4j.hkt.__;
public abstract class Label<T> {
private Label(){}
public abstract T apply(String s);
public abstract String unwrap(T lbl);
public abstract <f> __<f, String> subst(__<f, T> fa);
static Label<?> Label = new Label<String>() {
@Override
public String apply(String s) {
return s;
}
@Override
public String unwrap(String lbl) {
return lbl;
}
@Override
public <f> __<f, String> subst(__<f, String> fa) {
return fa;
}
};
public static void main(String[] args) throws IOException {
program(Label).run();
}
// "Slight" inconvenience vs scala: you have to write your program inside method(s) parametrized by the Label(s):
static <T> IO<Unit> program(Label<T> Label) {
class Toto {
private final T wrapped;
Toto(T wrapped){this.wrapped = wrapped;}
}
Toto toto = new Toto(Label.apply("Hello World"));
String unwrapped = Label.unwrap(toto.wrapped);
return IO.effect(() -> System.out.println(unwrapped));
}
}
@gneuvill
Copy link

Why not simply :

// poor man's newtype
interface $<A> { A __(); }

// Label is an alias for String
interface Label extends $<String> {}

void printLabel(Label label) {
  System.out.println(label.__());
}

printLabel("toto"); // doesn't compile

printLabel(() -> "toto"); // ok

@jbgi
Copy link
Author

jbgi commented May 25, 2017

Your example use a stateless lambda, but in the general case object instantiation via lambda is not cost-free. But yes it is simpler and actually practical.

@jbgi
Copy link
Author

jbgi commented Oct 15, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment