初学Haskell
问题如下:
-- The centroid of a list of points is a point whose x (and y) coordinates are
-- the means of the x (and y) coordinates of the points in the list.
--
-- You may assume the list contains at least one point.
--
-- > centroid [Pt 1 1, Pt 2 2]
-- Pt 1.5 1.5
-- > centroid [Pt (-1.5) 0, Pt 3 2, Pt 0 1]
-- Pt 0.5 1.0
尝试像这样编写代码
data Point = Pt Double Double deriving (Show, Eq)
centroid :: [Point] -> Point
pointX :: Point -> Double
pointX (Pt x y) = x
pointY :: Point -> Double
pointY (Pt x y) = y
pointsX :: [Point] -> [Double]
pointsX xs = map pointX xs
pointsY :: [Point] -> [Double]
pointsY xs = map pointY xs
average :: [Double] -> Double
average xs = (sum xs) `div` (genericLength xs)
centroid cenpoint = (Pt average(pointsX cenpoint) average(pointsY cenpoint))
我得到了
Project1.hs:35:22: error:
• Couldn't match expected type ‘([Double] -> Double)
-> [Double] -> Point’
with actual type ‘Point’
• The function ‘Pt’ is applied to four arguments,
but its type ‘Double -> Double -> Point’ has only two
In the expression:
(Pt average (pointsX cenpoint) average (pointsY cenpoint))
In an equation for ‘centroid’:
centroid cenpoint
= (Pt average (pointsX cenpoint) average (pointsY cenpoint))
|
35 | centroid cenpoint = (Pt average(pointsX cenpoint) average(pointsY cenpoint))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Project1.hs:35:25: error:
• Couldn't match expected type ‘Double’
with actual type ‘[Double] -> Double’
• Probable cause: ‘average’ is applied to too few arguments
In the first argument of ‘Pt’, namely ‘average’
In the expression:
(Pt average (pointsX cenpoint) average (pointsY cenpoint))
In an equation for ‘centroid’:
centroid cenpoint
= (Pt average (pointsX cenpoint) average (pointsY cenpoint))
|
35 | centroid cenpoint = (Pt average(pointsX cenpoint) average(pointsY cenpoint))
| ^^^^^^^
Project1.hs:35:33: error:
• Couldn't match expected type ‘Double’ with actual type ‘[Double]’
• In the second argument of ‘Pt’, namely ‘(pointsX cenpoint)’
In the expression:
(Pt average (pointsX cenpoint) average (pointsY cenpoint))
In an equation for ‘centroid’:
centroid cenpoint
= (Pt average (pointsX cenpoint) average (pointsY cenpoint))
|
35 | centroid cenpoint = (Pt average(pointsX cenpoint) average(pointsY cenpoint))
|
data Point = Pt { pointX,pointY :: Double } deriving (Show, Eq)
,你可以免费获得两个函数pointX
和pointY
。 - Will Ness