Functional Programming- Composition of Functions

Functional Programming- Composition of Functions

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

  4. Catamorphism Collapsable

  5. Applicative

  6. Monad Chainable

  7. Monoid Aggregatable

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 šŸŽŠ.

2024-02-18T09:14:04.705Z