Skip to content

HowTo: Write a View RevComp

Hannes Hauswedell edited this page Feb 27, 2018 · 1 revision

You are given this program:

#include <iostream>
#include <range/v3/all.hpp>
#include <string>

int main()
{
    std::string s{"ACGTTTATGT"};

    auto complement = [] (auto c)
    {
        switch (c)
        {
            case 'a': return 't';
            case 'A': return 'T';
            case 'c': return 'g';
            case 'C': return 'G';
            case 'g': return 'c';
            case 'G': return 'C';
            case 't': return 'a';
            case 'T': return 'A';
            default: return 'N';
        }
    };

    // make reverse complement view
    auto comp_view =                     // TODO: implement
    std::cout << comp_view << '\n';      // should print [A,C,A,T,A,A,A,C,G,T]

    // create infix from [1, 6)
    auto comp_view_inf =                 // TODO: implement
    std::cout << comp_view_inf << '\n';  // should print [C,A,T,A,A]

    // transform back
    auto orig_inf =                      // TODO: implement
    std::cout << orig_inf << '\n';       // should print [T,T,A,T,G]

    return 0;
}

Read through:

And fill in the "TODO: implement"

Solution: Click to expand

#include <iostream>
#include <range/v3/all.hpp>
#include <string>

int main()
{
    std::string s{"ACGTTTATGT"};

    auto complement = [] (auto c)
    {
        switch (c)
        {
            case 'a': return 't';
            case 'A': return 'T';
            case 'c': return 'g';
            case 'C': return 'G';
            case 'g': return 'c';
            case 'G': return 'C';
            case 't': return 'a';
            case 'T': return 'A';
            default: return 'N';
        }
    };

    // make reverse complement view
    auto comp_view = s | ranges::view::reverse | ranges::view::transform(complement);
    std::cout << comp_view << '\n';

    // create infix from [1, 7)
    auto comp_view_inf = comp_view | ranges::view::drop(1) | ranges::view::take(5);
    std::cout << comp_view_inf << '\n';

    // transform back
    auto orig_inf = comp_view_inf | ranges::view::reverse | ranges::view::transform(complement);
    std::cout << orig_inf << '\n';

    return 0;
}
Clone this wiki locally