Functional Programming: Composition of Functions

Functional Programming: Composition of Functions

·

5 min read

Input of one function comes from the output of another function.

👆 simple defination of function composition that i could find.

Main Ideas of Functional Programming.

  1. Function - here

  2. Compositions with Functions - This article

  3. Currying - here

  4. Catamorphism Collapsable - here

  5. Applicative

  6. Monad Chainable

  7. Monoid Aggregatable - here

In functional Programming, Composition takes the place of inheritance in OOP.

Composition > inheritance.

It's just better to use composition from the start. It's more flexible , it's more powerful , and it's really easy to do.

Creating a Compose Function

A lot of Javascript FP libraries like ramda, provide pipe() and compose() , which help us in creating composition of functions. Before moving to those,let's create our own example functions.

Here is an example of compose function which take two functions as argument.

let compose = function(fn1, fn2) {
return fn2(fn1)
}

//or

let compose = (fn1,fn2) => fn2(fn1)

Compose Vs Curry

Curry functions are always unary functions which take one argument per application.

Currying functions looks a lot similar pattern to composition, which often causes them to be mistaken for each other.

example of a curry function

const sum = a => b => a + b
sum(3)(5) // 8

Are 'Currying' and 'Composition' the same concept in javascript?

No.

First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument.

here, Notice the distinct way in which a curried function is applied, one argument at a time.

// not curried
const add = (x,y) => x + y;
add(2,3); // => 5

// curried
const add = x => y => x + y;
add(2)(3); // => 5

Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions.

const compose = f => g => x => f(g(x));

compose (x => x * 4) (x => x + 3) (2);
// (2 + 3) * 4
// => 20

The two concepts are closely related as they play well with one another. Generic function composition works with unary functions (functions that take one argument) and curried functions also only accept one argument (per application).

Function Composition

Function composition is a way of combining pure functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of one function is passed as the argument of the next, and the result of last one is the result of the whole.

Composition is a fancy term which means "combining".

In other words, we can often "combine" multiple steps either into one line of code, or into a new function to contain them

For example, if we want to find the sine of 30 degrees (remember sine uses radians) we could "compose" these two items into the single line: result = sin( degrees_to_radians( 30 ) ). This is the same as in math where we often see f(g(x)).

Example of a compose function which take more than two functions, and applies from left to right manner

We can write a function to compose as many functions as you like. In other words, compose() creates a pipeline of functions with the output of one function connected to the input of the next.

const compose = (...fns) => (x) => fns.reduceRight((y, fn) => fn(y), x);

This version takes any number of functions and returns a function which takes the initial value, and then uses reduceRight() to iterate right-to-left over each function, f, in fns, and apply it in turn to the accumulated value, y. What we're accumulating with the accumulator, y in this function is the return value for the function returned by compose().

Now we can write our composition like this:

const g = n => n + 1;
const f = n => n * 2;

// replace `x => f(g(x))` with `compose(f, g)`

const h = compose(f, g);
h(20); //=> 42

Composition in React

Creating a composition for Different buttons

const Button = props => {
  return <button>{props.text}</button>
}

const SubmitButton = () => {
  return <Button text="Submit" />
}

const LoginButton = () => {
  return <Button text="Login" />
}

Pass methods as props

A component can focus on tracking a click event, for example, and what actually happens when the click event happens is up to the container component:

const Button = props => {
  return <button onClick={props.onClickHandler}>{props.text}</button>
}

const LoginButton = props => {
  return <Button text="Login" onClickHandler={props.onClickHandler} />
}

const Container = () => {
  const onClickHandler = () => {
    alert('clicked')
  }

  return <LoginButton onClickHandler={onClickHandler} />
}

Using children

The props.children property allows you to inject components inside other components.

The component needs to output props.children in its JSX:

const Sidebar = props => {
  return <aside>{props.children}</aside>
}

and you embed more components into it in a transparent way:

<Sidebar>
  <Link title="First link" />
  <Link title="Second link" />
</Sidebar>
function TodoList({ todos, children }) {
  return (
    <section className='main-section'>
      <ul className='todo-list'>{
        todos.map((todo, i) => (
          <li key={ i }>{ children(todo) }</li>
        ))
      }</ul>
    </section>
  );
}

function App() {
  const todos = [
    { label: 'Write tests', status: 'done' },
    { label: 'Sent report', status: 'progress' },
    { label: 'Answer emails', status: 'done' }
  ];
  const isCompleted = todo => todo.status === 'done';
  return (
    <TodoList todos={ todos }>
      {
        todo => isCompleted(todo) ?
          <b>{ todo.label }</b> :
          todo.label
      }
    </TodoList>
  );
}

Notice how the App component doesn't expose the structure of the data. TodoList has no idea that there is label or status properties.

The so called render prop pattern is almost the same except that we use the render prop and not children for rendering the todo.

Your feedback and questions are Welcome. I will be improving the composition of this article but your opinions can make it better 🎊.

Did you find this article valuable?

Support Pratik Sharma by becoming a sponsor. Any amount is appreciated!

Â