Last active
September 11, 2019 20:52
-
-
Save vkrivopalov/37dad00a4c3fa32e5d2f727d449ffa5d to your computer and use it in GitHub Desktop.
ArrowMap implementation in Haskell and C++
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
#pragma once | |
#include <functional> | |
#include <optional> | |
template <typename K, typename V> | |
class arrow_map | |
{ | |
public: | |
using opt_value = std::optional<V>; | |
opt_value lookup(K&& key) { | |
return func(key); | |
} | |
void insert(K&& key, V&& value) { | |
func = [key = std::move(key), value = std::move(value), func = std::move(func)] (const K& k) -> opt_value { | |
if (k == key) { | |
return std::make_optional(value); | |
} | |
return func(k); | |
}; | |
} | |
void remove(K&& key) { | |
func = [key = std::move(key), func = std::move(func)] (const K& k) -> opt_value { | |
if (k == key) { | |
return std::nullopt; | |
} | |
return func(k); | |
}; | |
} | |
private: | |
std::function<opt_value(const K&)> func {[] (const K&) -> opt_value { return std::nullopt; } }; | |
}; |
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
import Prelude hiding (lookup) | |
class MapLike m where | |
empty :: m k v | |
lookup :: Ord k => k -> m k v -> Maybe v | |
insert :: Ord k => k -> v -> m k v -> m k v | |
delete :: Ord k => k -> m k v -> m k v | |
fromList :: Ord k => [(k,v)] -> m k v | |
newtype ArrowMap k v = ArrowMap { getArrowMap :: k -> Maybe v } | |
instance MapLike ArrowMap where | |
empty = ArrowMap (\_ -> Nothing) | |
lookup k (ArrowMap f) = f k | |
insert k v (ArrowMap f) = ArrowMap (\key -> if key == k then Just v else f key) | |
delete k (ArrowMap f) = ArrowMap (\key -> if key == k then Nothing else f key) | |
fromList [] = empty | |
fromList ((k,v):xs) = insert k v (fromList xs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment