Skip to content

Commit

Permalink
Solve 'Geometry Basics: Distance between points in 2D' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Oct 12, 2024
1 parent fc0866a commit c6d3a93
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/Distance.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module Distance (distance) where

-- https://www.codewars.com/kata/58dced7b702b805b200000be/train/haskell

import Preloaded (Point(..))

distance :: Point -> Point -> Double
distance p1 p2 = sqrt ((x p1 - x p2) ^ 2 + (y p1 - y p2) ^ 2)

-- #againwhatlearned: destructure Point structure:
-- distance (Point x1 y1) (Point x2 y2) = ...
4 changes: 3 additions & 1 deletion src/Preloaded.hs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ isWaveSorted xs
where
divvinger = divvy 3 2 xs

data Tree = Node { val :: Int, left, right :: Maybe Tree }
data Tree = Node {val :: Int, left, right :: Maybe Tree}

data Point = Point {x :: Double, y :: Double} deriving (Show)
29 changes: 29 additions & 0 deletions test/DistanceSpec.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module DistanceSpec (spec) where

import Preloaded (Point(..))
import Distance (distance)
import Test.Hspec
import Control.Monad (unless)

spec :: Spec
spec = do
it "example tests" $ do
test Point { x = 0, y = 1 } Point { x = 0, y = 0 } 1.0
test Point { x = 0, y = 3 } Point { x = 4, y = 0 } 5
test Point { x = 1, y = -1 } Point { x = 1, y = -1 } 0
test Point { x = 0, y = 0 } Point { x = 0, y = 0 } 0
test Point { x = 0, y = 0.3 } Point { x = 0.4, y = 0 } 0.5

epsilon :: Double
epsilon = 1e-6

test :: Point -> Point -> Double -> Expectation
test a b 0 = do
let actual = distance a b
message = "distance " ++ show a ++ " " ++ show b ++ ": expected actual value " ++ show actual ++ " to approximately equal expected value 0 ( accepted absolute error: " ++ show epsilon ++ " )"
unless (abs actual <= epsilon) $ expectationFailure message
test a b expected = do
let actual = distance a b
message = "distance " ++ show a ++ " " ++ show b ++ ": expected actual value " ++ show actual ++ " to approximately equal expected value " ++ show expected ++ " ( accepted relative error: " ++ show epsilon ++ " )"
unless (abs (actual - expected) <= epsilon * abs expected) $ expectationFailure message

0 comments on commit c6d3a93

Please sign in to comment.