Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell — Generate Coordinates From Ends of the Path

I have an input of [ ( (Int,Int) , (Int,Int) ) ] which is the coordinate of the ends of the path. All paths run either horizontally (same y-value for both ends) or vertically (same x-value for both ends).
So I want to write a function that generates all the coordinates of the path from the input.

For example, the input pair of ends is [((0, 0), (0, 3)), ((0, 2), (2, 2))](this is two paths), the output of the function I need is [[(0, 0), (0, 1), (0, 2), (0, 3)], [(0, 2), (1, 2), (2, 2)]]

getPaths :: [ ( (Integer,Integer) , (Integer,Integer) ) ] -> [[(Integer,Integer)]]
getPaths [((xa, ya), (xb, yb))]   
    | xa == xb : [(xa, yb + 1) | yb < ya]++
    | xa == xb : [(xa, ya + 1) | ya < yb]++
    | ya == yb : [(xa + 1, ya) | xa < xb]++
    | ya == yb : [(xb + 1, ya) | xb < xa]++

I’m not sure if its right, could anyone have a look at it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think it is better to first make a function that works with a single pair of coordinates:

path :: ((Int, Int), (Int, Int)) -> [(Int, Int)]
path = …

then getPaths is just a mapping of this:

getPaths :: [((Int, Int), (Int, Int))] -> [[(Int, Int)]]
getPaths = map path

as for the path, you can make use of ranges, indeed [x₁ .. x₂] will produce all (integral) values between x₁ and x₂ (both inclusive).

The function thus can be constructed with list comprehension with:

path :: ((Int, Int), (Int, Int)) -> [(Int, Int)]
path ((x₁, y₁), (x₂, y₂)) = [ … | … <- …, … <- … ]

where you still need to fill in the parts.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading