2016-04-19 8 views
-1

Ich versuche (PolyA a) und (PolyB a) zu Instanzen der Klasse Polynom, wo ich Coeffs, Coeffs, CoeffsB, CoeffsB implementieren möchte. Ich bin nicht ganz sicher, was ich falsch mache, weil ich eine Fehlermeldung bekomme, dass meine Funktionen für die Klasse Polynom nicht sichtbar sind. Irgendwelche Hilfe bitte?Haskell Typ Klasseninstanziation

class Polynomial p where 

--default implementations 
data PolyA a = Coeffs [a] 
      deriving (Show) 
data PolyB a = Const a | X (PolyB a) a 
      deriving (Show) 

--instances 
instance Polynomial (PolyA a) where 
    coeffs (Coeffs f)=f 
    fromCoeffs f= Coeffs f 

instance Polynomial (PolyB a) where 
coeffsB (Const f)= [f] 
coeffsB (X f a)= coeffsB f ++ [a] 
fromCoeffsB [] = error "Wrong Input!" 
fromCoeffsB [f]= Const f 
fromCoeffsB [email protected](_:t)= X (fromCoeffsB (init lis)) (last lis) 
+1

Sie haben in der 'class' Deklaration keine Funktionen definiert. – user2407038

Antwort

1

Der folgende Code kompiliert für mich:

class Polynomial p where 
    coeffs :: p a -> [a] 
    fromCoeffs :: [a] -> p a 

--default implementations 
data PolyA a = Coeffs [a] 
      deriving (Show) 
data PolyB a = Const a | X (PolyB a) a 
      deriving (Show) 

--instances 
instance Polynomial PolyA where 
    coeffs (Coeffs f)=f 
    fromCoeffs f= Coeffs f 

instance Polynomial PolyB where 
coeffs (Const f)= [f] 
coeffs (X f a)= coeffs f ++ [a] 
fromCoeffs [] = error "Wrong Input!" 
fromCoeffs [f]= Const f 
fromCoeffs [email protected](_:t)= X (fromCoeffs (init lis)) (last lis) 

Zusammenfassung der Änderungen:

  • Add-Methoden zum Polynomial Klassendeklaration.
  • Entfernen Sie die Typargumente in den Instanzdeklarationen.
  • Ändern coeffsB zu coeffs und fromCoeffsB zu fromCoeffs überall.
  • Ziehen Sie die PolyB Instanz Deklaration um ein Leerzeichen.
+0

Danke. Der Code funktioniert einwandfrei, aber jetzt, wenn ich versuche, von Coeffs [1,2,3,5] zu laufen, bekomme ich diese Fehlermeldung: : 176: 1: Keine Instanz für (Num a0) aus einer Verwendung von 'it' Die Variable vom Typ 'a0' ist mehrdeutig Hinweis: es gibt mehrere mögliche Fälle: Instanz Integral a => Num (GHC.Real.Ratio a) - definiert in 'GHC.Real' Instanz Num Ganzzahl - Definiert in 'GHC.Num' Instanz Num Double - Definiert in 'GHC.Float' ... plus drei weitere Im ersten Argument von 'print', nämlich 'es' – Vlad

+0

@Vlad Geben Sie es eine Typus-Signatur, wie in 'fromCoeffs [1,2,3,5] :: PolyA Int' oder' fromCoeffs [1,2,3, 5] :: PolyB Double'. –

+0

Ok, fair genug. Vielen Dank dafür! Ich habe ein Jahr lang in Haskell programmiert, kenne aber immer noch nicht jeden kleinen Aspekt davon. Vielen Dank für Ihre Hilfe, Kumpel! – Vlad