Estaba experimentando con las familias de tipo ayer y me encontré con un obstáculo con el siguiente código:Escribiendo Un polimórfica función en una familia Tipo
{-# LANGUAGE TypeFamilies #-}
class C a where
type A a
myLength :: A a -> Int
instance C String where
type A String = [String]
myLength = length
instance C Int where
type A Int = [Int]
myLength = length
main = let a1 = [1,2,3]
a2 = ["hello","world"]
in print (myLength a1)
>> print (myLength a2)
Aquí he un tipo asociado con la clase C y una función que calcula la longitud del tipo asociado. Sin embargo el código anterior me da este error:
/tmp/type-families.hs:18:30:
Couldn't match type `A a1' with `[a]'
In the first argument of `myLength', namely `a1'
In the first argument of `print', namely `(myLength a1)'
In the first argument of `(>>)', namely `print (myLength a1)'
/tmp/type-families.hs:19:30:
Couldn't match type `A a2' with `[[Char]]'
In the first argument of `myLength', namely `a2'
In the first argument of `print', namely `(myLength a2)'
In the second argument of `(>>)', namely `print (myLength a2)'
Failed, modules loaded: none.
Si, por el cambio "tipo" a "datos" del código se compila y funciona:
{-# LANGUAGE TypeFamilies #-}
class C a where
data A a
myLength :: A a -> Int
instance C String where
data A String = S [String]
myLength (S a) = length a
instance C Int where
data A Int = I [Int]
myLength (I a) = length a
main = let a1 = I [1,2,3]
a2 = S ["hello","world"]
in
print (myLength a1) >>
print (myLength a2)
¿Por qué la "longitud" no funciona como se esperaba ¿en el primer caso? Las líneas "tipo A Cadena ..." y "tipo A Int ..." especifican que el tipo "A a" es una lista, por lo que myLength debe tener los siguientes tipos respectivamente: "myLength :: [String] -> Int" o "myLength :: [Int] -> Int".
Parece que puede necesitar un '{- # LANGUAGE TypeSynonymInstances - #}' también, ya que 'String' es un sinónimo de tipo '[Char]', y sin la bandera GHC espera que se creen encabezados de instancia de las variables de tipo primitivo. – Raeez