Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's generally two approaches for this: The inductive definition you gave, or an abstract data type using something else for internal representation.</p> <p>Note that the inductive representation is not terribly efficient for large numbers; however, it can be lazy, which lets you do things like see which of two nats is larger without evaluating further than the size of the smaller one.</p> <p>An abstract data type is one which is defined in a separate module and does not export its constructors, examples being <code>IO</code> or <code>Data.Set.Set</code>. You can define something like this:</p> <pre><code>module Nat (Nat() {- etc. -} ) where newtype Nat = Nat { unNat :: Integer } </code></pre> <p>...where you export various operations on <code>Nat</code> such that, even though the <em>internal representation</em> is just <code>Integer</code>, you ensure that no value of type <code>Nat</code> is constructed holding a negative value.</p> <p>In both cases, if you want to use numeric literals, you'll need a definition of <code>fromInteger</code>, which is attached to the <code>Num</code> type class, which is completely wrong for natural numbers but oh well.</p> <p>If you don't mind making a broken instance just to get syntactic niceties, you can do something like this:</p> <pre><code>instance Num Nat where Zero + n = n n + Zero = n (Succ n1) + (Succ n2) = Succ . Succ $ n1 + n2 fromInteger 0 = Zero fromInteger i | i &gt; 0 = Succ . fromInteger $ i - 1 </code></pre> <p>...and so on, for the other functions. The same can be done for the abstract data type approach, just be careful to <em>not use <code>deriving</code> to get an automatic <code>Num</code> instance</em>, because it will happily break your non-negative constraint.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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