## Functor:

A Functor is simply something that can be mapped over.Let us consider an example in console:

map (\x -> x+1) [1,2,3]

output:

[2,3,4]

Yes, you are thinking the right array is a functor.

The function here map in the sense, the function is applied to every element in the array and it is stored again in the same location in our example i.e;

1 2 3 => in this the function will be applied to each element as follows

\1 -> 1+1

means it takes 1 and it will add 1 and replace 1 in that new array with 2.

similarly, it will be applied to each element in that array.

Note: The function in this example is called an inline function.

#### The map can be represented as <$> in purescript.

eg: (\x -> x+1) <$> [1,2,3]

Functors concept is only used for single arguments since we can pass a single array like a thing to function to perform map and return the same structure.

#### map with two variable:

Take a function that requires two variables that will take one variable and return rest of function that is ready to take another variable like

Int -> ( Int -> Int this function is returned first)Then apply map on the above return type by passing single argument we will get the result that we required just like the function with two parameters.

There are rules on how the map should behave so that it can qualify as a functor.

#### Functor follows the following laws:

The identity law:functor.map(x => x) ≡ functor

This means if you map over some functor with a function that simply returns the passed value (the identity function), the resulting functor should be same to the original functor:

map (\x -> x) [ 0, 1, 2, 3 ]

=> [ 0, 1, 2, 3 ]

Now, let’s look at the second law.

The composition law:

map (g . f ) = map g . map f

“The second law says that composing two functions and then mapping the resulting function over a functor should be the same as first mapping one function over the functor and then mapping the other one.”

Happy Coding.....

## No comments:

## Post a Comment