Recursive Lambda in C ++

Source: Internet
Author: User

The C ++ Standards Committee is really too rigid. Since Lambda is added to C ++, the standard definition of Lambda is applied step by step without adding a self-Reference Mechanism of Lambda. After searching for half a day, except for the fix point + Y Combinator, which could make 99% of students dizzy, one of the most practical solutions is to import Lambda bind to STD :: function <...>.

My code that requires recursive lambda:

  void print_output() const { // use recursive lambda        std::string str;        std::function<void(state_id_t,state_id_t,char_t)> lambda =        [&](state_id_t source,state_id_t target,char_t c) {            str.push_back(c);            if (is_term(target))                cout <<str << '\n';            for_each_move(target, lambda);            str.resize(str.size()-1); // pop_back        };        for_each_move(initial_state, lambda);    }

The tree shape automata code is printed in DFS order. for various reasons (memory, speed, and conciseness), a general for_each_move is designed to traverse each direct target of the specified state.

If there is recursive lambda, this code should be more concise and efficient (assuming [[] is the symbol that references Lambda itself ):

    void print_output() const { // use recursive lambda        std::string str;        for_each_move(initial_state, [&](state_id_t, state_id_t target, char_t c) {            str.push_back(c);            if (is_term(target))                cout <<str << '\n';            for_each_move(target, [[]]);            str.resize(str.size()-1); // pop_back        });    }

This is the intention of C ++ committee! It is to make everyone uncomfortable, to show their pure academic, their pure mathematic!
It is easy to add a self-referenced symbol!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.