https://dzone.com/articles/functor-and-monad-examples-in-plain-java?edition=188561&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=dd%202016-06-29

Here is the code of a functor

What does it say?

- Functor encapsulates value(s) T, F<T>
- Functor has a map method
- The map method accepts a function convert object T to Object R
- 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

- A Functor encapsulating one Customer
- A Functor encapsulating a list of Customer
- 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

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