Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created December 3, 2016 18:05
Show Gist options
  • Save jbrains/ff3065f4abe0d8d0a7effb8f86c1b122 to your computer and use it in GitHub Desktop.
Save jbrains/ff3065f4abe0d8d0a7effb8f86c1b122 to your computer and use it in GitHub Desktop.
PLEASE tell me that there's a better way in Java to write this
// findPrice : String -> Option<Price>
// Option comes from Atlassian's fugue library https://docs.atlassian.com/fugue/4.3.0/fugue/apidocs/index.html
// I want the equivalent of
// case (maybePrice) {
// none => display.displayProductNotFoundMessage(barcode)
// some(price) => display.displayPrice(price)
// }
catalog.findPrice(barcode)
.<Runnable>fold(
() -> (() -> display.displayProductNotFoundMessage(barcode)),
(price) -> (() -> display.displayPrice(price))
).run();
@manuelp
Copy link

manuelp commented Dec 5, 2016

My two minutes attempt, using Functional Java. Obviously, untested and from the top of my head!

/* 
 * Assuming:
 *
 * barcode :: Barcode
 * display#displayProductNotFoundMessage() :: F<Barcode, IO<Unit>>
 * display#displayPrice() :: F<Price, IO<Unit>>
*/
catalog.findPrice(barcode) // Option<Price>
    .map(display.displayPrice()) // Option<IO<Unit>>
    .orSome(
	    display.displayProductNotFoundMessage().f(barcode) // IO<Unit>
	    )
    .run();

If the only side effect is printing a String, we could simplify it like this:

/* 
 * Assuming:
 *
 * barcode :: Barcode
 * display#displayProductNotFoundMessage() :: F<Barcode, String>
 * display#displayPrice() :: F<Price, String>
*/
String res = catalog.findPrice(barcode) // Option<Price>
    .map(display.displayPrice()) // Option<String>
    .orSome(
	    display.displayProductNotFoundMessage().f(barcode) // String
	    );
fancyPrint(res);

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