Saturday, July 2, 2016

functor and monad

Here is a good article explained functor and monad using java.

Here is the code of a functor
What does it say?

  1. Functor encapsulates value(s) T, F<T>
  2. Functor has a map method 
  3. The map method accepts a function convert object T to Object R
  4. The map method returns a Functor which encapsulates R, F<R>

Functor makes it easy to use unified API over various data structures.
In this method, the input parameter could be
  1. A Functor encapsulating one Customer
  2. A Functor encapsulating a list of Customer
  3. A Promise encapsulating a Customer object which will become available in future. (Promise implements Functor interface).

The logic is separated into 2 parts.
One is the logic in the map object in each Functor. This is dealing the wrapped object data structure. For example, the map function of FOptional only applies the convert function on the wrapped object when it is not null. The map function of FList iterates the list and apply the function on each item in the list.
The other logic is to convert Object T to Object R. This is in the function, the input parameter of the map method.

Monad is Functor. If the function passed into map method returns a Functor, the map method returns a double wrapped Functor. Having a functor in functor ruins composition and fluent chaining. Monad has a flatMap method to avoid this issue. m[x].flatMap(f) is the same as f(x). m[x] means a monad which is wrapping x.

Here is the article explaining functors in javascript

A functor is a data structure you can map functions over with the purpose of lifting values from a container, modifying them, and then putting them back into a container.

Structures such as functors are prohibited from throwing exceptions, mutating elements on a list, or altering a function’s behavior. Their practical purpose is to create a context that allows you to securely manipulate and apply operations to values, without changing the original value.

No comments:

Post a Comment