J'expérimentais avec les familles de type hier et a couru dans un obstacle avec le code suivant:L'écriture d'un polymorphes de fonction dans un type de famille
{-# 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)
Ici, je suis un type associé à la classe C et une fonction qui calcule la longueur du type associé. Cependant, le code ci-dessus me donne cette erreur:
/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, mais je change « type » à « données » le code compile et fonctionne:
{-# 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)
Pourquoi ne « longueur » fonctionne pas comme prévu dans le premier cas? Les lignes "type A String ..." et "type A Int ..." spécifient que le type "A a" est une liste donc myLength doit avoir respectivement les types suivants: "myLength :: [String] -> Int" ou "myLength :: [Int] -> Int".
Il semble que vous ayez besoin d'un '{- # LANGUAGE TypeSynonymInstances - #}', car 'String' est un synonyme de' [Char] ', et sans le drapeau, GHC s'attend à ce que les têtes d'instance soient construites des variables de type primitif. – Raeez