How to make the same types with different behavior in Haskell?

I use Haskell and the functional graph library to represent graphs. There are two ways to compare graphs, directly, over a function equal to or over another function, I wrote isIsomorph. I want to use a hash map to collect graphs. To do this, I need to create an instance of the Eq class for my graphs. But I need two hash maps, first for graphs that are compared by function equal, and the second for graphs that are compated by the isIsomorph function.


If i do

type Fragment = Gr Atom Bond {-- Gr is a type constructor from the Functional Graph Library} instance Eq (Gr Atom Bond) where g == g1 = equal g g1 instance Eq Fragment where g == g1 = isIsomorph g g1 

I have expected error

 Duplicate instance declarations: instance [overlap ok] Eq (Gr Atom Bond) -- Defined at HLab.hs:45:10 instance [overlap ok] Eq Fragment -- Defined at HLab.hs:48:10 

Due to the fact that type decalcation is just a wrapper.

I can use another way

 data Fragment = Fragment {fgraph :: Gr Atom Bond} instance Eq (Gr Atom Bond) where g == g1 = equal g g1 instance Eq Fragment where Fragment g == Fragment g1 = isIsomorph g g1 

This is correct, but I used constructor data of the "heavy" type, this method is also inconvenient, I need to get graphs from fragments using the additional function fgraph.

Is there any β€œbeautiful” and β€œtrue” way to separate these types in different parts of the code?

+4
source share
1 answer

The "beautiful" and the "true" way to separate these types in different parts of the code? consists in using newtype instead of data : for all system purposes they are different (in particular, you can define different instances of the type class), but they have the same representation at runtime, and there are no additional features with data :

 newtype Fragment = Fragment {fgraph :: Gr Atom Bond} instance Eq (Gr Atom Bond) where g == g1 = equal g g1 instance Eq Fragment where Fragment g == Fragment g1 = isIsomorph g g1 

You will need to convert between graphs and fragments when trying to use the graph functions on fragments.

+11
source

Source: https://habr.com/ru/post/1500530/


All Articles