What is this C++14 construct called which seems to chain lambdas?

后端 未结 3 931
一个人的身影
一个人的身影 2021-02-14 01:47

This is a follow-up question on this one: Lambda-Over-Lambda in C++14, where the answers explain the code.

It is about a lambda that creates another lambda which when ca

3条回答
  •  长情又很酷
    2021-02-14 02:23

    I looked around a bit and turns out the main functionality is reordering the function calls as explained in the answers to the original question.

    So world(hello(stdout)); is rewritten to terminal(stdout)(hello)(world); which more generally could be written as compose(stdout)(hello)(world);.

    • In Haskell this would written as world . hello $ stdout and is called function composition.
    • In clojure it would be (-> stdout hello world) and is called the "thread-first" macro

    I think it is only useful with decent partial application which lambdas provide a little bit, so we could have compose(4)([](int x){ return x + 7; })([](int x){ return x * 2; })([](int x){ return x == 22; }); which should return true if my calculation (and blind coding) is any good.

    or to emphasize the partial application:

    auto add7 = [](int x){ return x + 7; };
    auto dbl = [](int x){ return x * 2; };
    auto equal22 = [](int x){ return x == 22; };
    assert(compose(4)(add7)(dbl)(equals22));
    

    1 major issue with this implementation is probably that the result can't be evaluated because in the end a lambda is returned, so the construction in this answer might be better suited (function separated by comma instead of parenthesis).

提交回复
热议问题