vector map
template<typename T> | |
struct vector { int length; T* data; }; | |
using vector_int = vector<int>; | |
using vector_float = vector<float>; | |
// F is a function type that takes T and returns R | |
// Map takes a vector<T>, and F and returns vector<R> | |
template<class T, class F> | |
auto Map(vector<T> input, F func){ | |
using R = decltype(func(input.data[0])); | |
vector<R> result { input.length, new R[input.length] }; | |
for(int i=0; i < input.length; i++) | |
result.data[i] = func(input.data[i]); | |
return result; | |
} | |
#include <math.h> | |
#include <stdio.h> | |
int main() { | |
vector_int ivec { 5, new int[5] {1, 2, 3, 4, 5} }; | |
vector_float fvec = Map(ivec, sqrtf); | |
for(int i = 0; i < fvec.length; i++) | |
printf("%d -> %f\n", i, fvec.data[i]); | |
} |
struct vector_int { int length; int * data; }; | |
struct vector_float { int length; float * data; }; | |
// type_level function : vector_of<float>::type = vector_float etc. | |
template<typename T> struct vector_of { }; | |
template<> struct vector_of<float> { using type = vector_float; }; | |
template<> struct vector_of<int> { using type = vector_int; }; | |
// TCollection has .length and array of T .data | |
// F is a function taking T and returning R | |
// Map takes a TCollectoin and F and returns a vector of Rs | |
template<class TCollection, class F> | |
auto Map(TCollection input, F func){ | |
using R = decltype(func(input.data[0])); | |
using vector_of_R = typename vector_of<R>::type; | |
vector_of_R result { input.length, new R[input.length] }; | |
for(int i=0; i < input.length; i++) | |
result.data[i] = func(input.data[i]); | |
return result; | |
} | |
#include <math.h> | |
#include <stdio.h> | |
int main() { | |
vector_int ivec { 5, new int[5] {1, 2, 3, 4, 5} }; | |
vector_float fvec = Map(ivec, sqrtf); | |
for(int i = 0; i < fvec.length; i++) | |
printf("%d -> %f\n", i, fvec.data[i]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment