Home > Back-end >  How can I change the type of my Haskell function
How can I change the type of my Haskell function

Time:10-17

I have a function that has a type:

mulPoly :: Poly -> Poly -> Poly

But I want to have a type:

mulPoly :: (Num a, Eq a) => Poly a -> Poly a -> Poly a

How can I transform this Haskell code:

data Poly = [Int] deriving (Show, Eq)

mulPoly :: Poly -> Poly -> Poly
mulPoly (a:as) bs = 
  addPoly (scale a bs) (0 : mulPoly as bs)

to this type:

data Poly a = P [a] deriving (Show, Eq)

mulPoly :: Poly a -> Poly a -> Poly a

here are the functions addPoly and scale already defined on type Poly a

addPoly :: (Num a, Eq a) => Poly a -> Poly a -> Poly a
addPoly (P as) (P bs) = P (inner as bs)
  where
    inner [] ys = ys
    inner xs [] = xs
    inner (x:xs) (y:ys) = (x y) : inner xs ys

scale :: (Num a, Eq a) => a -> Poly a -> Poly a
scale 0 (P (x:xs)) = P []
scale y (P []) = P []
scale y (P (x:xs)) = P (map (y*) (x:xs))

CodePudding user response:

Just need to do some wrapping and unwrapping in appropriate places:

mulPoly :: (Num a, Eq a) => Poly a -> Poly a -> Poly a
mulPoly (P []) _ = P []   -- you were missing this case
mulPoly (P (a:as)) bs =
    addPoly (scale a bs) 
            (shift1 $ mulPoly (P as) bs)
  where
    shift1 (P bs) = P (0:bs)

We just need to pay attention what takes raw lists as arguments, and what takes them wrapped under the P tag, and adjust your original code accordingly.

  • Related