I'm very new to Haskell and functional programming in general, so I don't really know how to make this code idiomatic:
type Coord = Double
data Point = Point Coord Coord Coord deriving Show
type Polyline = [Point]
-- Add a point to a polyline
addPoint :: Polyline -> Point -> Polyline
addPoint line p = p:line
line :: Polyline
line = []
constructLine :: Polyline -> Polyline
constructLine line =
let
p1 = Point 2 4 87
p2 = Point 3 7 2
p3 = Point 23 4 8
in addPoint (addPoint (addPoint line p1) p2) p3
main :: IO()
main = do
putStrLn ( show (constructLine line))
My problem is in the constructLine
function. If I want to add a lot of points the nested addPoint
functions are going to be a problem. How can I factor this? And do you see other things that could be improved?
The multiple call to addPoints could be replaced by a fold. As suggested in a comment, reversing your addPoint function would make things easier:
So then your constructLine function could build a temporary list of the points to add add use a fold:
This does not break the encapsulation (you can replace your implementation of Polyline by something else than a list of Point) and uses the new points in the order they're going to end up at (p3 in front of p2, etc.)