How to use IntMap with various types of keys?

I have an entry in a document that uses two IntMaps:

data Doc = Doc { kernels :: IntMap Kernel, nodes :: IntMap Node }

But I found that the keys to both IntMaps have different meanings, and I cannot separate them in two different types and I get no errors when using socket kernel types and node types. I want to have functions that check the keys of the kernel map and the node map and do not allow confusion. For instance:

someFunction :: Doc -> KernelKey -> NodeKey -> a
someFunction doc k1 k2 = .....

Instead of current:

someFunction :: Doc -> Int -> Int -> a
someFunction doc k1 k2 = .... -- warning check twice k1 and k2

Is it possible? Or I will change from IntMapto Map.

thank

+5
source share
2 answers

You can use newtypeso that the wrappers around Intdiffer in their meaning.

newtype KernelKey = KernelKey Int
newtype NodeKey = NodeKey Int

someFunction :: Doc -> KernelKey -> NodeKey -> a
someFunction doc (KernelKey k1) (NodeKey k2) = ...

, IntMap , , KernelKey NodeKey, .

, newtype , .

+10

API IntMap Doc. .

data DocValue = DocKernel Kernel
              | DocNode Node
data DocKey = KernelKey Int
            | NodeKey Int

docLookup :: DocKey -> Doc -> Maybe DocValue

, API . , .

newtype NodeKey = NodeKey Int
newtype KernelKey = KernelKey Int
lookupDocNode :: NodeKey -> Doc -> Maybe Node
lookupDocKernel :: KernelKey -> Doc -> Maybe Kernel

. . , , . , , .

+3

All Articles