Haskell - Turning a list into a list of object with index

Viewed 78

I do have a list in Haskell with the coordinates of some points, like:

[[5.8,2.7,4.1,1.0],[6.2,2.2,4.5,1.5],[5.6,2.5,3.9,1.1]]

Already made a "Point" datatype

data Point = Point {
    pointSelf :: Int,
    coordinates:: [Float]
} deriving (Show)

I would like to make that list [[Float]] to become a list of [Point], with the attribute "pointSelf" being his index, how should I make it?

I am kinda new at Haskell and functional programming...

1 Answers

You can use zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] to enumerate over two lists concurrently, and apply a function on the two items of the list. You thus can construct the Points with:

zipWith Point [0 ..] myCoords

with myCoords the list of coordinates, so for the sample data, myCoords is [[5.8,2.7,4.1,1.0],[6.2,2.2,4.5,1.5],[5.6,2.5,3.9,1.1]].

Related