Thunk函数

Thunk函数

1.前言

最早的thunk函数起源来自于“传值调用”(call by value) 和“传名调用”(call by name)之争。
对于:

    let x = 1;

    function fn(m){
        return m*2;
    }

    fn(x+1);
  • 传值调用的主张:fn(x+1)==fn(2);//执行前就进行计算
  • 传名调用的主张:fn(x+1) == (1+1)*2;//只在执行的时候才进行计算

广义上thunk函数就是“传名调用”的实际表现,表示

    let x = 1;
    
    function fn(thunk){
        return thunk()*2;
    }

    function thunk(){
        return x+1;
    }

    fn(thunk);

此时x+1是在fn被执行后才进行计算的,名副其实的传名调用。传名调用的好处是使用时计算,不浪费资源。

2. javascript中的thunk函数

javascript是【传值调用】,在js中thunk函数表示的并非是替换【表达式】而是替换【多参数函数】,将其替换为单参数版本,并只使用callback作为参数。


//正常函数
let fn = fs.readFile(fileName,callback);

//thunk转换
function thunk(fileName){
    return function(callback){
        return fn(fileName,callback);
    } 
}

let fnToThunk = thunk(fileName);

fnToThunk(callback1);
fnToThunk(callback1);
......

任何函数只要存在回调就可以thunk转换,下面就是个thunk函数转换器:


function thunk(fn){
    return function(){
        let args = Array.from(arguments);
        return function (callback){
            let wholeArgs = args.concat(callback);
            return fn.apply(this,wholeArgs);
        }
    }
}

//正常函数
let fn = function(arg1,arg2...,callback){};
let fnToThunk = thunk(fn)(arg1,arg2,...);

fnToThunk(calback1);
fnToThunk(calback2);
fnToThunk(calback3);

3.Thunkify函数

Thunkify函数是在Thunk基础上对callback执行次数做出限定的一个特化版本。例子如下:

        function sum(a, b, callback) {
            const total = a + b
            callback(total);
            callback(total);
        }


        function thunkify(fn) {
            return function () {
                let args = Array.from(arguments);
                return function (callback) {
                    let called;
                    let proxyCallBack = function () {
                        if (called) {
                            return;
                        }
                        called = true;
                        callback.apply(null, Array.from(arguments));
                    }
                    let wholeArgs = [...args, proxyCallBack];
                    try{
                        return fn.apply(this, wholeArgs);
                    }
                    catch(err){
                        callback(err);
                    }
                }
            }
        }

        let turnFn = thunkify(sum);
        turnFn(1, 2)(console.log);

        //结果只会执行一遍
        3

4.后记

thunk函数实际上就是curry函数是它的一个子集,它规定了最后一个参数必须是callback函数,其他完全一样。thunk主要使用场景是generator函数的流程管理。这个将在后续的文章中介绍。
参考:Thunk函数的含义和用法;

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如qsort 等函数需要函数指针才能回调 用此函数库可以将成员函数指针转为普通函数指针 测试代码如下 #include <stdio.h> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <math.h> using cmpfunc = int(__cdecl*)(const void*, const void*); using DebugArrayFunc = void(__stdcall *)(std::string &out;); #include "thunk.h" class MySort { public: int Rule; MySort(int a):Rule(a){} // 回调函数 template<typename T> int __cdecl sort(const void* a, const void* b); }; class Test { public: std::vector<int> mm; void Sort(int (*comp)(const void *,const void *)) { return qsort(mm._Myfirst,mm.size(),sizeof(int),comp); } void Entry(DebugArrayFunc func) { std::string string; cmpfunc comp; TemplateThunk athunk; // 正序 comp = (cmpfunc)athunk.GetCall(&MySort;::sort<int>, &MySort;(0)); Sort(comp); func(string); std::cout << string << std::endl; // 逆序 comp = (cmpfunc)athunk.GetCall(&MySort;::sort<int>, &MySort;(1)); Sort(comp); func(string); std::cout << string << std::endl; } }; class CallBack { public: std::vector<int> *pthis; CallBack(std::vector<int> *ff):pthis(ff){} void __stdcall DebugArray(std::string &out;) { char buff[100]; char *aa = buff; for each (auto a in *pthis) { aa += sprintf(aa, "%d ", a); } out.assign(buff); } }; void main() { TemplateThunk athunk; Test tt; tt.mm = { 1, 3, 7, 8, 5, 6, 4, 2, 3, 10 }; tt.Entry(athunk.GetCall(&CallBack;::DebugArray,&CallBack;(&tt;.mm))); } template <typename T> int __cdecl MySort::sort(const void* a, const void* b) { return Rule ? *static_cast<const T*>(a)-*static_cast<const T*>(b) : *static_cast<const T*>(b)-*static_cast<const T*>(a); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值