public calculateNameLength( name : Monad<String>) : Monad<Natural> {
return name.map(m -> m.size());
}
Lense supports the concept of Monad. A monad is a special container type that allows operations to occur on the contained type without explicitly requiring the boxing and unboxing of the contained instances. Monads are a special case of the Decorator pattern where all operations return a new object and transform the decorated type in some way.
Because all monads are containers, they rely on decorating a contained object. In Lense we do this simply by calling the monads constructor. You can also create enhancements to facilitate some more common encapsulations.
The most common operation is to transform a monad object to another monad object of the same type operating in the contained elements. This is done by the map function.
public calculateNameLength( name : Monad<String>) : Monad<Natural> {
return name.map(m -> m.size());
}
Some times a map operation will end up in an object of type Monad<Monad<T>>
. Normally we would like to end up in a Monad<T>
type, so we can use the flatMap operation:
let name : String?
let length : Natural? = name.flaMap(m -> calculateNameLength(m));