Last active
December 27, 2019 04:45
-
-
Save talyian/d3f838fc27c91a52d4e38b1f5c3b023d to your computer and use it in GitHub Desktop.
vector map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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