128k views
3 votes
p3_unzip :: [(a,b)] -> ([a], [b]) Write a function that takes a list of two-tuples and returns a tuple of two lists -- the first containing the first element of each tuple, and the second the second element (i.e., the reverse of "zip"). Examples: > p3_unzip [('a',1),('b',5),('c',8)] ("abc",[1,5,8])

1 Answer

6 votes

Answer:

C++.

Step-by-step explanation:

#include <iostream>

#include<tuple>

using namespace std;

////////////////////////////////////////////////////////////

tuple<char*, int*> p3_unzip(tuple<char, int>* list, int count) {

char* list1 = new char[count];

int* list2 = new int[count];

for (int i=0; i<count; i++) {

tuple<char, int> temp = list[i];

list1[i] = get<0>(temp);

list2[i] = get<1>(temp);

}

tuple<char*, int*> new_tuple;

get<0>(new_tuple) = list1;

get<1>(new_tuple) = list2;

return new_tuple;

}

int main() {

tuple<char, int>* list;

int count = 0;

////////////////////////////////////////

cout<<"How many tuples? ";

cin>>count;

list = new tuple<char, int>[count];

cout<<endl;

char a;

int b;

tuple<char, int> temp;

for (int i=0; i<count; i++) {

cout<<"tuple "<<i+1<<" char: ";

cin>>a;

get<0>(temp) = a;

cout<<"tuple "<<i+1<<" int: ";

cin>>b;

get<1>(temp) = b;

list[i] = temp;

cout<<endl;

}

////////////////////////////////////////

tuple<char*, int*> new_tuple = p3_unzip(list, count);

char* list1 = get<0>(new_tuple);

int* list2 = get<1>(new_tuple);

cout<<"Returned tuple:([";

for (int i=0; i<count-1; i++) {

cout<<list1[i]<<", ";

}

cout<<list1[count-1]<<"],[";

for (int i=0; i<count-1; i++) {

cout<<list2[i]<<", ";

}

cout<<list2[count-1]<<"])";

////////////////////////////////////////

delete[] list, list1, list2;

return 0;

}

User Evaldaz
by
6.5k points