1

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)
sjakobi
  • 3,546
  • 1
  • 25
  • 43
Bery Purda
  • 33
  • 3

1 Answers1

4

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I want to return a list of floats in the function "ossz", so I changed everything like you suggested, but it doesn'n work If I want to return a list. It looks like this now: `ossz :: [Pont] -> [Float] ossz [] = 0.0 ossz (h : t) = (szamol h) ++ (ossz t)` Also, the szamul function looks like this now: `szamol :: Pont -> Float szamol (0.0, 0.0) = 0.0 szamol (x,y) = sqrt (x*x + y*y)` – Bery Purda Apr 05 '20 at 12:12
  • @BeryPurda: then you use `map` without the `sum`. – Willem Van Onsem Apr 05 '20 at 12:13