Are thunk and function currying the same?

牧云@^-^@ 提交于 2020-05-23 11:59:45

问题


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

回答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

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.




回答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.



来源:https://stackoverflow.com/questions/61584833/are-thunk-and-function-currying-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!