Note that there are some explanatory texts on larger screens.

plurals
  1. POType constraints for automatic function constraint deduction in Haskell
    primarykey
    data
    text
    <p>For educational purposes I am playing around with trees in Haskell. I have <code>Tree a</code> type defined like this</p> <pre><code>data Tree a = EmptyTree | Node a (Tree a) (Tree a) </code></pre> <p>and a lot of functions that share a basic constraint - <code>Ord a</code> - so they have types like</p> <pre><code>treeInsert :: Ord a =&gt; a -&gt; Tree a -&gt; Tree a treeMake :: Ord a =&gt; [a] -&gt; Tree a </code></pre> <p>and so on. I can also define <code>Tree a</code> like this</p> <pre><code>data Ord a =&gt; Tree a = EmptyTree | Node a (Tree a) (Tree a) </code></pre> <p>but I can not simplify my functions and omit the extra <code>Ord a</code> to be as the following:</p> <pre><code>treeInsert :: a -&gt; Tree a -&gt; Tree a treeMake :: [a] -&gt; Tree a </code></pre> <p>Why does Haskell (running with <code>-XDatatypeContexts</code>) not automatically deduce this constraint? It seems to to be quite obvious for me that it should. Why am I wrong? </p> <p>Here is some example source code</p> <pre><code>data (Eq a, Ord a) =&gt; Tree a = EmptyTree | Node a (Tree a) (Tree a) treeInsert :: a -&gt; Tree a -&gt; Tree a treeInsert a EmptyTree = Node a EmptyTree EmptyTree treeInsert a node@(Node v left right) | a == v = node | a &gt; v = Node v left (treeInsert a right) | a &lt; v = Node v (treeInsert a left) right mkTree :: [a] -&gt; Tree a mkTree [] = EmptyTree mkTree (x:xs) = treeInsert x (mkTree xs) </code></pre> <p>I am getting this</p> <pre><code>Tree.hs:5:26: No instance for (Ord a) arising from a use of `Node' In the expression: Node a EmptyTree EmptyTree In an equation for `treeInsert': treeInsert a EmptyTree = Node a EmptyTree EmptyTree Failed, modules loaded: none. </code></pre>
    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.
 

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