如何更改 Haskell 函数的类型
How can I change the type of my Haskell function
我有一个函数,其类型为:
mulPoly :: Poly -> Poly -> Poly
但是我想要一个类型:
mulPoly :: (Num a, Eq a) => Poly a -> Poly a -> Poly a
如何转换此 Haskell 代码:
data Poly = [Int] deriving (Show, Eq)
mulPoly :: Poly -> Poly -> Poly
mulPoly (a:as) bs =
addPoly (scale a bs) (0 : mulPoly as bs)
此类型:
data Poly a = P [a] deriving (Show, Eq)
mulPoly :: Poly a -> Poly a -> Poly a
这里是函数 addPoly
和 scale
已经在类型 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))
只需要在适当的地方做一些包装和解包:
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)
我们只需要注意什么将原始列表作为参数,什么将它们包装在 P
标签下,并相应地调整您的原始代码。
我有一个函数,其类型为:
mulPoly :: Poly -> Poly -> Poly
但是我想要一个类型:
mulPoly :: (Num a, Eq a) => Poly a -> Poly a -> Poly a
如何转换此 Haskell 代码:
data Poly = [Int] deriving (Show, Eq)
mulPoly :: Poly -> Poly -> Poly
mulPoly (a:as) bs =
addPoly (scale a bs) (0 : mulPoly as bs)
此类型:
data Poly a = P [a] deriving (Show, Eq)
mulPoly :: Poly a -> Poly a -> Poly a
这里是函数 addPoly
和 scale
已经在类型 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))
只需要在适当的地方做一些包装和解包:
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)
我们只需要注意什么将原始列表作为参数,什么将它们包装在 P
标签下,并相应地调整您的原始代码。