2016-01-30 20 views
0
instance Num Polinom where 
    let 
     zmnoziKoef :: [Rational] -> [Rational] -> [Rational] 
     zmnoziKoef _ [] = [] 
     zmnoziKoef [] _ = [] 
     zmnoziKoef (x:xs) (y:ys) = (x * y) : pomnoziKoef x ys `sestejKoef` (xs `zmnoziKoef` (y:ys)) 
     sestejKoef :: [Rational] -> [Rational] -> [Rational] 
     sestejKoef xs [] = xs 
     sestejKoef [] ys = ys 
     sestejKoef (x:xs) (y:ys) = (x + y):(sestejKoef xs ys) 
     pomnoziKoef :: Rational -> [Rational] -> [Rational] 
     pomnoziKoef a = map (a *) 

    negate (Polinom koef) = Polinom $ pomnoziKoef (-1) koef 
    (Polinom koef1) + (Polinom koef2) = Polinom $ sestejKoef koef1 koef2 
    (Polinom koef1) * (Polinom koef2) = Polinom $ zmnoziKoef koef1 koef2 
    fromInteger x = Polinom $ [fromInteger x] 

所以這段代碼有效,但是有一種方法可以創建一組輔助函數,這樣我就不必在每次定義之後編寫它們。輔助功能時的情況下,如何分組?

像這樣:

instance Num Polinom where 
    negate (Polinom koef) = Polinom $ pomnoziKoef (-1) koef 
    (Polinom koef1) + (Polinom koef2) = Polinom $ sestejKoef koef1 koef2 
    (Polinom koef1) * (Polinom koef2) = Polinom $ zmnoziKoef koef1 koef2 
    fromInteger x = Polinom $ [fromInteger x] 
     where 
      zmnoziKoef :: [Rational] -> [Rational] -> [Rational] 
      zmnoziKoef _ [] = [] 
      zmnoziKoef [] _ = [] 
      zmnoziKoef (x:xs) (y:ys) = (x * y) : pomnoziKoef x ys `sestejKoef` (xs `zmnoziKoef` (y:ys)) 

      sestejKoef :: [Rational] -> [Rational] -> [Rational] 
      sestejKoef xs [] = xs 
      sestejKoef [] ys = ys 

      sestejKoef (x:xs) (y:ys) = (x + y):(sestejKoef xs ys) 

      pomnoziKoef :: Rational -> [Rational] -> [Rational] 
      pomnoziKoef a = map (a *) 
+2

把他們在頂層。每個'let'和'where'必須用一個準確申報有關 - 有沒有辦法「共享」一個'類中的所有聲明中let',或者在所有的任何聲明之中。 – user2407038

回答

2

letwhere只能在通過設計一個表達式或聲明被使用。如果你想使用它們作爲輔助功能不止一個聲明只是把他們在頂層:

zmnoziKoef :: [Rational] -> [Rational] -> [Rational] 
zmnoziKoef _ [] = [] 
zmnoziKoef [] _ = [] 
zmnoziKoef (x:xs) (y:ys) = (x * y) : pomnoziKoef x ys `sestejKoef` (xs `zmnoziKoef` (y:ys)) 

sestejKoef :: [Rational] -> [Rational] -> [Rational] 
sestejKoef xs [] = xs 
sestejKoef [] ys = ys 

sestejKoef (x:xs) (y:ys) = (x + y):(sestejKoef xs ys) 

pomnoziKoef :: Rational -> [Rational] -> [Rational] 
pomnoziKoef a = map (a *) 

instance Num Polinom where 
    negate (Polinom koef) = Polinom $ pomnoziKoef (-1) koef 
    (Polinom koef1) + (Polinom koef2) = Polinom $ sestejKoef koef1 koef2 
    (Polinom koef1) * (Polinom koef2) = Polinom $ zmnoziKoef koef1 koef2 
    fromInteger x = Polinom $ [fromInteger x] 

如果您希望這通過使用導出列表保持私有的模塊,你可以簡單地避開它們導出:

module MyModule(funcA, funcB, funcC) where 
... 

在上面的代碼只funcAfuncBfuncC和將導入模塊(加上所有實例)時導出。