2

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)
} 

Function currying

function multiply(a, b, c) {
    return a * b * c;
}

function multiply(a) {
    return (b) => {
        return (c) => {
            return a * b * c
        }
    }
}

2 Answers2

3

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

export default function thunkMiddleware({ dispatch, getState }) {
  return next => 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

let applyCurrying = curriedFn(fn);
let result = applyCurrying(a)(b)(c);

A trivial implementation of curriedFn:

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

In currying, each function takes exactly one parameter.

Utsav Patel
  • 2,789
  • 1
  • 16
  • 26
  • For those wondering about **why** and when to use currying, this blog post explains it well: https://medium.com/dailyjs/why-the-fudge-should-i-use-currying-84e4000c8743 – Tschallacka May 20 '20 at 07:15
  • 1
    Isn't the above thunk example same as saying, thunkMiddleware = a => next => action => ( do compuation with a,next, action ) , where a has properties dispatch and getState. In thiat case, how is it differnt than currying? – user6317694 Jul 21 '22 at 15:39
1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375