Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

The error is very dumb but it´s been an hour trying to solve it... Could anyone help me?.

Thank you!!

like image 539
Sierra Avatar asked Dec 17 '22 10:12

Sierra


2 Answers

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.

like image 183
hammar Avatar answered Jan 02 '23 10:01

hammar


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

like image 36
Daniel Lyons Avatar answered Jan 02 '23 10:01

Daniel Lyons