I want to work with a list of coordinates [Haskell]

482 Views Asked by At

So I need to work with a list of coordinates, I already made a type like this:

type Pont = (Float, Float)

And I need to return a list of Floats calculated from the points I got. What I did so far:

szamol :: Pont -> Float
szamol 0.0 = 0.0
szamol (x,y) = 10^(1/2)*((x^2)+(y^2))

ossz :: [Pont] -> [Pont]
ossz [] = []
ossz (h,t) = szamol h ++ ossz t

it gives me this error:

ERROR "Hazi.hs":6 - Cannot justify constraints in explicitly typed binding
*** Expression    : szamol
*** Type          : Pont -> Float
*** Given context : ()
*** Constraints   : (Integral a, Fractional a)
1

There are 1 best solutions below

2
On BEST ANSWER

The pattern 0.0 in:

szamol 0.0 = 0.0

makes no sense. A Pont Point is a 2-tuple of Floats, not a single Float, so you can define this as:

szamol :: Pont -> Float
szamol (0.0, 0.0) = 0.0
szamol (x,y) = 10^(1/2)*((x^2)+(y^2))

Using 10^(1/2) will fail, since the ^ operator expects the second operand to be of a type that is a member of the Integral typeclass. You can use 10**(1/2).

Using 10**(1/2) will give you the square root of 10 (so ≈ 3.16), and will not calculate the square root of the sum of squares.

You thus likely want to use:

szamol :: Pont -> Float
szamol (0.0, 0.0) = 0.0
szamol (x,y) = sqrt (x*x + y*y)

In your ossz function, you make three mistakes:

  1. the return type should be Float here;
  2. you sum up with (+), not with (++) and
  3. the data constructor for a list "cons" is (:), not (,):
ossz :: [Pont] -> Float
ossz [] = []
ossz (h : t) = szamol h + ossz t

Here it might be better to use a combination of sum :: (Foldable t, Num a) => t a -> a and map :: (a -> b) -> [a] -> [b]:

ossz :: [Pont] -> Float
ossz = sum . map szamol

EDIT: if you want to return a list of Floats, then you can map:

ossz :: [Pont] -> [Float]
ossz = map szamol

or with explicit recursion:

ossz :: [Pont] -> [Float]
ossz [] = []
ossz (h : t) = szamol h : ossz t