Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You might want an <a href="http://en.wikipedia.org/wiki/Algebraic_data_type" rel="noreferrer">ADT</a> that can only be constructed with golden ratio numbers then write myfun to accept that data type.</p> <p>I've assumed Integer as a base type, but you could use others (ex: Double or Float) or even be polymorphic.</p> <p>1) Make the ADT</p> <pre><code>module Golden (Gold, getGold, buildGold) where data Gold = G Integer Integer getGold :: Gold -&gt; (Integer, Integer) getGold (G x y) = (x, y) buildGold :: Integer -&gt; Integer -&gt; Maybe Gold buildGold x y | isGolden x y = Just (G x y) | otherwise = Nothing </code></pre> <p>Notice this module exports the <code>Gold</code> type but not the constructor (namely, not <code>G</code>). So the only way to get a value of type <code>Gold</code> is with <code>buildGold</code> which performs a run-time check - but only one - so the values of Gold can be used and assumed to be a golden ratio by all the consumers without checking.</p> <p>2) Use the ADT to build <code>myfun</code></p> <pre><code>myfun :: Gold -&gt; ??? myfun g = expr where (x, y) = getGold g </code></pre> <p>Now if you try to call <code>myfun</code> with a non-golden number (a value not of type <code>Gold</code>) then you will get a compile time error.</p> <p>Recap To build golden numbers <code>buildGold</code> function must be used, which forces the number to be checked.</p> <p>Notice what gets checked when! You have a compile time guarantee that <code>myfun</code>, and all other functions you want to use with <code>Gold</code>, are always provided golden ratios. The program input (from user, network, or where ever) still needs runtime checks and that's what <code>buildGold</code> provides; obviously there's never going to be a program that can promise the human won't type something undesirable.</p> <p>The alternatives given in the comments to your question are also worthy of consideration. An ADT is slightly heavy weight if all you need is a single function, <code>myfun</code>, that can fail then just have <code>myfun :: (Integer, Integer) -&gt; Maybe ???</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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