Voglio fare una superclasse di Num, chiamato lineareHaskell: fare una superclasse di Num
class Linear a where
add :: a -> a -> a
instance (Num a) => Linear a where
add = (+)
ottengo l'errore:
Illegal instance declaration for `Linear a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Linear a'
Da quello che ho capito, qualcosa sulla linea di instance (Num a) => Linear a where
non è corretto. (Compilare se uso le bandiere: -XFlexibleInstances -XUndecidableInstances
)
C'è un modo per ottenere questo risultato senza utilizzare quelle bandiere spaventose? (e cosa al mondo è indecidibile per il codice sopra ??)
UPDATE: Aggiunto il tipo polinomiale a Lineare.
newtype Polynomial a = Polynomial (a,[a]) deriving Show-- list of coeffients
instance (Linear a) => Linear (Polynomial a)
where
add (Polynomial (c1, l1)) (Polynomial (c2, l2))
= Polynomial (add c1 c2, zipWith (add) l1 l2)
p1 = Polynomial (0, [3,4,5])
p2 = Polynomial (0, [])
main = putStrLn $ show ((add p1 p2):: Polynomial Int)
Dopo aver aggiunto polinomiale, essa non viene compilato anche con quelle bandiere e dare l'errore:
Overlapping instances for Linear (Polynomial Int)
arising from a use of `add'
Matching instances:
instance Num a => Linear a -- Defined at Algebra.hs:22:10-28
instance Linear a => Linear (Polynomial a)
-- Defined at Algebra.hs:25:10-44
In the first argument of `show', namely
`((add p1 p2) :: Polynomial Int)'
In the second argument of `($)', namely
`show ((add p1 p2) :: Polynomial Int)'
In the expression: putStrLn $ show ((add p1 p2) :: Polynomial Int)
puoi per favore indicare perché sono necessari; e l'indecidibilità fa paura :) – Karan
In Haskell, molte cose hanno nomi spaventosi di cui nessuno si preoccuperebbe per un secondo in altre lingue. – leftaroundabout