• [^] # Re: Haskell newbie

    Posté par . En réponse au journal Les types fantômes. Évalué à 4.

    Le type fantôme peut être avantageusement déclaré via newtype:

    the type is checked at compile time, at run time the two types can be treated essentially the same, without the overhead or indirection normally associated with a data constructor.

    On peut ensuite aussi jouer avec l'extension OverloadedStrings comme suit:

    {-# Language OverloadedStrings #-}
    module PhantomType where
    import GHC.Exts(IsString(..))
    data Firstname
    data Lastname
    newtype P a = P { fromPhantom :: String }
    instance IsString (P a) where
     fromString = P
    prénom = "George" :: P Firstname
    nom = "Abitbolt" :: P Lastname
    data Client = Client (P Firstname) (P Lastname)
    client1 = Client prénom nom
    client2 = Client "Charles" "Bronson"
    client3 = Client ("PasBill" :: P Firstname) ("PasGates" :: P Lastname)
    
    

    Du coup on a plus du tout besoin d'utiliser de constructeur.
    Mais on peut toujours mettre de façon explicite le type de la chaîne.

    client4 = Client nom prénom
    
    
    test = nom == prénom
    
    

    ne compileront pas.