-
Notifications
You must be signed in to change notification settings - Fork 2
Collection Monad
Collection monad is arguably among the most frequently used of all the monads in the monad bestiary. It works by applying the operations to all possible values to produce a collection of all possible results.
Monadologie automatically converts collections and maps to their monadic form, so
there is no need to call extra method like state or write for state and writer
monads, respectively. It is worth noting that any change to the collection/map to
make it a monad is internal to the monad comprehension. From the outside, it is your
plain old collection. This is accomplished by using categories to extend the collection.
One example is given in the README file, where it is asked to show whether a knight can go from position A to position B on the chess board in exactly three moves.
In another example we'll write a function that finds all Pythagorean triples up to a given number (Pythagorean triple is a set of three integers that satisfy Pythagorean theorem):
import static hr.helix.monadologie.MonadComprehension.foreach
def pythags(a) {
foreach {
z = takeFrom { 1..a }
x = takeFrom { 1..z }
y = takeFrom { x..z }
guard { x**2 + y**2 == z**2 }
yield { [x, y, z] }
}
}
assert pythags(12) == [[3, 4, 5], [6, 8, 10]]In the above example we're using ranges. Collection monad accepts Collections (Lists, Sets, ..., including Ranges)
and Maps.