yoyo
yoyo

Reputation: 21

how to calculate the distance using Pos haskell

Say I defined this type: type Pos = (Int, Int)

I'd like to use above type to calculate thhe distance between two points, and I wrote like this:

type Pos = (Int, Int)
distancee :: Pos -> Pos -> Float
distancee Pos (x1,y1) (x2,y2) = sqrt((dx*dx)+(dy*dy))
    where
        dx = x2 - x1
        dy = y2 - y1

I dont really know how to use Pos, and above is not right, so could you please tell me how can I fix that?

Upvotes: 2

Views: 108

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

There are two problems here. The first one is that a Point is a type alias for a 2-tuple. It thus has no specific data constructor. This means that the head of the distancee should look like:

type Pos = (Int, Int)

distancee :: Pos -> Pos -> Float
distancee (x1,y1) (x2,y2) = …

A second problem is that subtracting two Ints results in an Int, multiplying two Ints results in an Int, and adding two Ints together will produce an Int. This is because the (-) :: Num a => a -> a -> a, (*) :: Num a => a -> a -> a, and (+) :: Num a => a -> a -> a all have a signature where the two operands and the result all have the same type. We can not apply sqrt :: Floating a => a -> a for an Int, since it requires a type that is a member of the Floating typeclass. We can make use of fromIntegral :: (Integral a, Num b) => a -> b to convert an item of an Integral type into an object of a Num type with:

distancee :: Pos -> Pos -> Float
distancee (x1,y1) (x2,y2) = sqrt (fromIntegral (dx*dx + dy*dy))
    where dx = x2 - x1
          dy = y2 - y1

Upvotes: 5

Related Questions