Skip to content

Instantly share code, notes, and snippets.

@haskellcamargo
Last active July 18, 2022 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save haskellcamargo/3c93bc279bd7dba9477d to your computer and use it in GitHub Desktop.
Save haskellcamargo/3c93bc279bd7dba9477d to your computer and use it in GitHub Desktop.
Maybe monad implementation in Java 7
package br.com.ngi.monad;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Just<T> extends Maybe<T> {
private T mValue;
public Just(T data) {
mValue = data;
}
@Override
public T fromJust() {
return mValue;
}
@Override
public boolean isNothing() {
return false;
}
@Override
public Maybe bind(Callable fn) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<T> future = executorService.submit(fn);
return Monad.maybe(future);
}
@Override
public boolean isJust() {
return true;
}
@Override
public Maybe maybe(T def, Callable<T> fn) {
return this.bind(fn);
}
}
package br.com.ngi.refreshlayout;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import java.util.concurrent.Callable;
import br.com.ngi.monad.Maybe;
import br.com.ngi.monad.Monad;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView x = null;
final Maybe list = Monad.maybe(x);
list.bind(new Callable() {
@Override
public Object call() throws Exception {
Log.d("MainActivity", list.fromJust().toString());
return null;
}
});
}
}
package br.com.ngi.monad;
import java.util.concurrent.Callable;
public abstract class Maybe<T> {
public abstract T fromJust();
public abstract boolean isJust();
public abstract boolean isNothing();
public abstract Maybe<T> bind(Callable<T> runnable);
public abstract Maybe<T> maybe(T def, Callable<T> fn);
}
package br.com.ngi.monad;
import java.util.concurrent.Callable;
public class Nothing<T> extends Maybe {
@Override
public T fromJust() throws RuntimeException {
throw new RuntimeException("Cannot call fromJust() on Nothing");
}
@Override
public boolean isJust() {
return true;
}
@Override
public boolean isNothing() {
return true;
}
@Override
public Maybe<T> bind(Callable fn) {
return this;
}
@Override
public Maybe<T> maybe(Object def, Callable fn) {
return (Maybe<T>) Monad.maybe(def);
}
}
@PercyPham
Copy link

In Nothing class, isJust() and isNothing() are currently return true. That isJust() should return false.

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