deseo de definir la siguiente clase de tipos Mapping
:Haskell: clases tipo de pregunta
{-# LANGUAGE MultiParamTypeClasses #-}
class Mapping k v m where
empty :: m v
insert :: k -> v -> m v -> m v
search :: k -> m v -> Maybe v
delete :: k -> m v -> m v
Un ejemplo de Mapping
es Data.Map.Map
{-# LANGUAGE ..., FlexibleInstances #-}
instance Ord k => Mapping k v (Map.Map k) where
empty = Map.empty
search = Map.lookup
insert = Map.insert
delete = Map.delete
Y ahora quiero crear un tipo de Trie :: * -> * -> * -> *
como
{-# 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 => Mapping [k] v (Trie m k) where
search [] tree = trValue tree
search (x:xs) tree =
search xs =<< search x (trChildren tree)
Hasta ahora todo bien, ahora también quiero definir Trie
's insert
y empty
, y ahí es donde me meto en problemas.
voy a discutir empty
porque es más simple y insert
necesita de todos modos .. Si intento esto:
instance Mapping k (Trie m k v) m => Mapping [k] v (Trie m k) where
empty = Trie { trValue = Nothing, trChildren = empty }
...
y eso me sale el siguiente error:
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}
tengo intenté y traté de resolverlo pero fallé.
¿Alguien sabe cómo hacerlo funcionar? ¿Es posible?
BTW, sugiero eliminar el 'v' de la definición de clase de tipo (pero déjelo en las firmas de los métodos). No lo necesita, al menos para todas las estructuras que ha dado hasta ahora, ya que todas tomarán cualquier tipo de contenido, y todo se simplifica. –