Last active
January 22, 2016 07:33
-
-
Save bryanedds/61d0ff5ff890025f0a0a to your computer and use it in GitHub Desktop.
C++ map, filter, fold
This file contains hidden or 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
#ifndef xtd_container_hpp | |
#define xtd_container_hpp | |
#include <cstddef> | |
#include <initializer_list> | |
#include <vector> | |
#include "prelude.hpp" | |
template<typename Cr, typename Fn> | |
Cr map(const Cr& source, const Fn& mapper) | |
{ | |
constrain_as_container(Cr); | |
Cr mapped(source.capacity()); | |
for (val& elem : source) | |
mapped.insert(std::end(mapped), mapper(elem)); | |
return mapped; | |
} | |
template<typename Cr, typename Fn> | |
Cr filter(const Cr& source, const Fn& predicate) | |
{ | |
constrain_as_container(Cr); | |
Cr filtered; | |
for (val& elem : source) | |
if (predicate(elem)) | |
filtered.insert(std::end(folded), elem); | |
return filtered; | |
} | |
template<typename Cr, typename El, typename Fn> | |
El fold(const Cr& source, const El& seed, const Fn& folder) | |
{ | |
constrain_as_container(Cr); | |
El state = seed; | |
for (val& elem : source) | |
state = folder(state, elem); | |
return state; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment