Note that there are some explanatory texts on larger screens.

plurals
  1. POHaskell: type classes question
    text
    copied!<p>I wish to define the following typeclass <code>Mapping</code>:</p> <pre><code>{-# LANGUAGE MultiParamTypeClasses #-} class Mapping k v m where empty :: m v insert :: k -&gt; v -&gt; m v -&gt; m v search :: k -&gt; m v -&gt; Maybe v delete :: k -&gt; m v -&gt; m v </code></pre> <p>One instance of <code>Mapping</code> is <code>Data.Map.Map</code></p> <pre><code>{-# LANGUAGE ..., FlexibleInstances #-} instance Ord k =&gt; Mapping k v (Map.Map k) where empty = Map.empty search = Map.lookup insert = Map.insert delete = Map.delete </code></pre> <p>And now I want to create a type <code>Trie :: * -&gt; * -&gt; * -&gt; *</code> such as</p> <pre><code>{-# LANGUAGE ..., UndecidableInstances #-} data Trie m k v = Trie { trValue :: Maybe v, trChildren :: m (Trie m k v) } instance Mapping k (Trie m k v) m =&gt; Mapping [k] v (Trie m k) where search [] tree = trValue tree search (x:xs) tree = search xs =&lt;&lt; search x (trChildren tree) </code></pre> <p>So far so good, now I also want to define <code>Trie</code>'s <code>insert</code> and <code>empty</code>, and that's where I get into problems.</p> <p>I will discuss <code>empty</code> because it's simpler and <code>insert</code> needs it anyhow.. If I try this:</p> <pre><code>instance Mapping k (Trie m k v) m =&gt; Mapping [k] v (Trie m k) where empty = Trie { trValue = Nothing, trChildren = empty } ... </code></pre> <p>and that makes me get the following error:</p> <pre><code>Could not deduce (Mapping k (Trie m k1 v) (m k1)) from the context (Mapping [k1] v (Trie m k1), Mapping k1 (Trie m k1 v) (m k1)) arising from a use of `empty' at test.hs:27:49-53 Possible fix: add (Mapping k (Trie m k1 v) (m k1)) to the context of the instance declaration or add an instance declaration for (Mapping k (Trie m k1 v) (m k1)) In the `trChildren' field of a record In the expression: Trie {trValue = Nothing, trChildren = empty} In the definition of `empty': empty = Trie {trValue = Nothing, trChildren = empty} </code></pre> <p>I've tried and tried to solve it but failed.</p> <p>Does anyone know how to make it work? Is it even possible?</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