Skip to content

Commit 259fa0d

Browse files
authored
Fixes the 'Line' type center calculation formula (#220)
Changes the formula to x=(p1.x+p2.x)/2 y=(p1.y+p2.y)/2 Reuses the 'getCenter' function in the centerShape example implementation.
1 parent 082072b commit 259fa0d

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

exercises/chapter5/src/Data/Picture.purs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ data Point = Point
1111
, y :: Number
1212
}
1313

14+
getX :: Point -> Number
15+
getX (Point p) = p.x
16+
17+
getY :: Point -> Number
18+
getY (Point p) = p.y
19+
1420
showPoint :: Point -> String
1521
showPoint (Point { x, y }) =
1622
"(" <> show x <> ", " <> show y <> ")"
@@ -37,7 +43,7 @@ origin = Point { x: 0.0, y: 0.0 }
3743
getCenter :: Shape -> Point
3844
getCenter (Circle c r) = c
3945
getCenter (Rectangle c w h) = c
40-
getCenter (Line (Point s) (Point e)) = Point { x: s.x - e.x, y: s.y - e.y }
46+
getCenter (Line (Point s) (Point e)) = Point { x: (s.x + e.x) / 2.0, y: (s.y + e.y) / 2.0 }
4147
getCenter (Text loc text) = loc
4248

4349
type Picture = Array Shape

exercises/chapter5/test/no-peeking/Solutions.purs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,12 @@ import Data.Picture
99
, Picture
1010
, Point(Point)
1111
, Shape(Circle, Rectangle, Line, Text)
12-
, origin
1312
, bounds
13+
, getCenter
14+
, getX
15+
, getY
1416
, intersect
17+
, origin
1518
)
1619
import Data.Picture as DataP
1720
import Math as Math
@@ -59,14 +62,15 @@ circleAtOrigin = Circle origin 10.0
5962
centerShape :: Shape -> Shape
6063
centerShape (Circle c r) = Circle origin r
6164
centerShape (Rectangle c w h) = Rectangle origin w h
62-
centerShape (Line (Point s) (Point e)) =
65+
centerShape line@(Line (Point s) (Point e)) =
6366
(Line
6467
(Point { x: s.x - deltaX, y: s.y - deltaY })
6568
(Point { x: e.x - deltaX, y: e.y - deltaY })
6669
)
6770
where
68-
deltaX = (e.x + s.x) / 2.0
69-
deltaY = (e.y + s.y) / 2.0
71+
delta = getCenter line
72+
deltaX = getX delta
73+
deltaY = getY delta
7074
centerShape (Text loc text) = Text origin text
7175

7276
scaleShape :: Number -> Shape -> Shape

0 commit comments

Comments
 (0)