문제 설명
좌표 목록으로 작업하고 싶습니다 [Haskell] (I want to work with a list of coordinates [Haskell])
좌표 목록으로 작업해야 하므로 이미 다음과 같은 유형을 만들었습니다.
type Pont = (Float, Float)
그리고 얻은 점에서 계산된 Float 목록을 반환해야 합니다. 지금까지 한 작업:
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
이 오류가 발생합니다.
ERROR "Hazi.hs":6 ‑ Cannot justify constraints in explicitly typed binding
*** Expression : szamol
*** Type : Pont ‑> Float
*** Given context : ()
*** Constraints : (Integral a, Fractional a)
참조 솔루션
방법 1:
The pattern 0.0
in:
szamol 0.0 = 0.0
makes no sense. A Pont
Point
is a 2‑tuple of Float
s, 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:
- the return type should be
Float
here; - you sum up with
(+)
, not with(++)
and - 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 Float
s, 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
(by Bery Purda、Willem Van Onsem)