Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you know in advance the set of properties a molecule might have, you could define a sum type:</p> <pre><code>data Property = Mass Float | CatalogNum Int | Comment String </code></pre> <p>If you want this type to be extensible, you could use Data.Dynamic as another answer suggests. For instance:</p> <pre><code>data Molecule = Molecule { name :: Maybe String, graph :: Gr Atom Bond, property :: [(String,Dynamic)] } deriving (Show) mass :: Molecule -&gt; Maybe Float mass m = case lookup "mass" (property m) of Nothing -&gt; Nothing Just i -&gt; fromDynamic i </code></pre> <p>You could also get rid of the "stringly-typed" <code>(String,a)</code> pairs, say:</p> <pre><code>-- in Molecule: -- property :: [Dynamic] data Mass = Mass Float mass :: Molecule -&gt; Maybe Mass mass m = ... </code></pre> <p>Neither of these attempts gives much type safety over just parsing out of <code>(String,String)</code> pairs since there is no way to enforce the invariant that the user creates well-formed properties (short of wrapping properties in a new type and hiding the constructors in another module, which again breaks extensibility).</p> <p>What you might want are Ocaml-style polymorphic variants. You could look at <a href="http://hackage.haskell.org/packages/archive/vinyl/latest/doc/html/Data-Vinyl-Lens.html" rel="nofollow">Vinyl</a>, which provides type-safe extensible records.</p> <p>As an aside, you might want to get rid of the <code>Maybe</code> wrapper around the list of properties, since the empty list already encodes the case of no properties.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload