简体   繁体   English

地图必须包含所有可能的键?

[英]Map which must contain all possible keys?

Haskell has multiple data structures like Map key value , either using a tree or hash map internally. Haskell有多个数据结构,如Map key value ,在内部使用树或哈希映射。 When using this data structure, it is possible that when doing a lookup, the key will not be present. 使用此数据结构时,可能在执行查找时,密钥将不存在。

In my use case the set of possible keys is finite (technically they are in both Enum and Ord ) and I am only interested in having a map with all keys present. 在我的用例中,可能键的集合是有限的(技术上它们在EnumOrd )并且我只对存在所有键的映射感兴趣。

How to create a map-like data structure that guarantees all keys are present in the map, ie it can have a non-partial function lookup :: Map key value -> key -> value (possibly with constraints on key type, Ord or Hashable or anything else)? 如何创建一个类似于地图的数据结构,保证地图中存在所有键,即它可以具有非部分函数lookup :: Map key value -> key -> value (可能具有key类型的约束, OrdHashable还是其他什么东西)? Is there something like this already? 有没有这样的东西?

In other words: I want a data structure that can only be queried if all possible keys were inserted. 换句话说:我想要一个只有在插入所有可能的密钥时才能查询的数据结构。 I could use regular Map with fromMaybe , but I don't want to have to specify default value – I want to guarantee at type level that default value is never needed. 我可以使用带有fromMaybe常规Map ,但我不想指定默认值 - 我想在类型级别保证永远不需要默认值。

The structure you are looking for is just a function : Key -> Value . 您正在寻找的结构只是一个功能: Key -> Value You can insert (or in fact replace) value with the following 您可以使用以下内容插入 (或实际替换)值

insert :: (Key -> Value) -> Key -> Value -> (Key -> Value)
insert f k v k' = if k == k' then v else f k'

keys and values function are trivial to implement (you just need your Key type to be an Enum ). keysvalues函数实现起来很简单(只需要将Key类型作为Enum )。 The compiler can warn you if a function is partial or not (ultimately, which ever data structure you use, you can't stop someone to insert an undefined value). 编译器可以警告您函数是否是部分函数(最终,您使用的是哪种数据结构,您无法阻止某人插入undefined值)。

You should look into a technique known as memo(ization) tries . 你应该研究一种称为memo(ization)尝试的技术 A memo trie for a function type A -> B is a data type that represents a function of that type as a data structure that records all the argument/result combinations. 函数类型A -> B的备忘录是一种数据类型,它表示该类型的函数作为记录所有参数/结果组合的数据结构。 Some links you may look through: 您可以浏览一些链接:

But to make a long story short, memo tries in Haskell come out as lazily constructed, potentially infinite search trees where the value for each key is computed by applying the function that we're memoizing. 但是长话短说,Haskell中的备忘录试图以懒惰的方式构建,可能是无限的搜索树,其中每个键的值通过应用我们正在记忆的函数来计算。

Memo tries may not be exactly what you're looking for, but there's a good chance the technique can be adapted to whatever your goal is. 备忘录尝试可能并不完全符合您的要求,但这种技术很有可能适应您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM