Skip to content Skip to sidebar Skip to footer

Are Thunk And Function Currying The Same?

When I learn thunk, I think they are like function currying. Why is it called thunk? Thunk function add(x, y){ return x + y } function thunk() { return add(10, 20) } Functio

Solution 1:

No they are quite different.

However, both thunks and currying have applications in functional programming.

Thunks

Thunks are a functional programming technique used to delay computation.

This helps us greatly in context of redux.

So, what do we do when we want to delay computation when we dispatch an action? We use thunks as a middleware.

It is very simple

exportdefaultfunctionthunkMiddleware({ dispatch, getState }) {
  returnnext =>action =>typeof action === 'function' ?
      action(dispatch, getState) :
      next(action);
} 

This is largely the implementation of thunks in redux-thunk.

It basically just checks whether the dispatched action is a function, if not it just passes it as is.

You can read the core implementation here. It is just 14 lines.

Currying

Currying is converting a single function of n arguments into n functions with a single argument each.

So for example if we have a function that takes three parameters a,b & c

let result = fn(a,b,c)

When we apply currying to it, then it becomes

letapplyCurrying = curriedFn(fn);
letresult = applyCurrying(a)(b)(c);

A trivial implementation of curriedFn:

constcurriedFn = a => b =>c => ( do compuation with a,b,c );

In currying, each function takes exactly one parameter.

Solution 2:

No, they're quite different. Both might be functions, but that's it. A thunk does not take any parameters, so that you can just evaluate it (and evaluating it at a point of your choosing is the entire purpose), while function currying is all about parameters and their representation.

Post a Comment for "Are Thunk And Function Currying The Same?"