Created
October 18, 2014 23:36
-
-
Save mariogarcia/3a084f32a9e83ec7c490 to your computer and use it in GitHub Desktop.
How Try monad can be used in Groovy
This file contains 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 static java.lang.Integer.* | |
import static groovyfp.categories.Fn.* | |
def zero = { 0 } | |
def parse = { String c -> return { parseInt(c) } } | |
def addOne = { Integer y -> y + 1 } | |
def addToListIfValue = { Integer z -> z ? List(z) : List() } | |
// Getting every item in the list | |
bind(List("2a","3","4")) { String x -> | |
bind( | |
recover( | |
fmap(Try(parse(x)), addOne), // try to add one | |
Try(zero) // get 0 in case of failure | |
), | |
addToListIfValue // add partial result to a list | |
) | |
}.typedRef.value | |
// Building what is going to be done per every item | |
def validNumbers = { String x -> | |
bind( | |
recover( | |
fmap(Try(parse(x)), addOne), | |
Try(zero) | |
), | |
addToListIfValue | |
).typedRef.value | |
} | |
def list = ["2a","3","4"] | |
// We are using collectMany method which flattens all | |
// nested list and ignore empty lists | |
def result = list.collectMany(validNumbers) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment