monads (version 0.0.0.9000)

monad-generics: Monad generics.

Description

To make a class a monad, you need to define three generics: fmap, bind, and join. fmap takes a non-monad function, and applies it to a monad by unwrapping, applying, and rewrapping. bind apply a function that takes a regular value and returns a monad, by unwrapping and applying. join collapses a monad that's nested inside itself.

Usage

fmap(.m, .f, ...)

bind(.m, .f, ...)

join(.m)

Arguments

.m

The monad

.f

A function, formula, or atomic vector.

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function with two arguments, .x or . and .y. This allows you to create very compact anonymous functions with up to two inputs.

If character or integer vector, e.g. "y", it is converted to an extractor function, function(x) x[["y"]]. To index deeply into a nested list, use multiple values; c("x", "y") is equivalent to z[["x"]][["y"]]. You can also set .null to set a default to use instead of NULL for absent components.

...

Additonal arguments passed on to .f.

Details

Any object with a fmap method is called a functor.

Examples

Run this code
# Functions are functors
add1 <- function(x) x + 1
add2 <- function(x) x + 2

add3 <- add1 %>>% add2
add3(10)

Run the code above in your browser using DataLab