开发者

Solving Equations in Haskell

I have to do an exercise and I´m pretty lost... I need to do an instance for Ord with polynomials. This is my try:

data Pol = P [(Float,Int)] deriving Show

instance Ord Pol where
  (Pol a) > (Pol b)  = (maxGrado a) > (maxGrado b) || ((maxGrado a) == (maxGrado b) && (maxCoe a) > (maxCoe b))
  (Pol a) < (Pol b)  = (maxGrado a) < (maxGrado b) || ((maxGrado a) == (maxGrado b) && (maxCoe a) < (maxCoe b))

maxGrado :: [(Float,Int)] -> Int
maxGrado [] = 0
maxGrado ((c,g):xs) = g  

maxCoe :: [(Float,Int)] -> Int
maxCoe [] = 0
maxcoe ((c,g):xs) = c

--error:

ERROR file:.\Febrero 2011.hs:32 - Undefined data constructor "Pol"

T开发者_如何学Che error is very dumb but it´s been an hour trying to solve it... Could anyone help me?.

Thank you!!


data Pol = P [(Int, Int)]

In this declaration, Pol is the type constructor, and P is the only data constructor for this data type. In general, a data type can have multiple data constructors so that's why we have this distinction.

A simple rule is that you should use the type constructor whenever you're talking about types, and the data constructor whenever you're talking about values.

In this case, you should use Pol in the instance head, but P in the patterns for your functions.

instance Ord Pol where
  (P a) > (P b)  = ...
  (P a) < (P b)  = ...

Also note that type constructors and data constructors live in different namespaces, and are never used in the same context. This means that it's ok for them to have the same name.

data Pol = Pol [(Int, Int)]

This would also work.


I think you want to use P instead of Pol in your instance functions. Pol is the type, P is the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜