How to apply a function on each element in a list in Haskell?

Mia.M picture Mia.M · Jun 23, 2016 · Viewed 18.4k times · Source

I have a list of tuples here, and I want to apply function dir..on the first element in each tuple. How can I do that? Thanks a lot in advance!

[ ("grid", gridResponse),
("graph", graphResponse),
("image", graphImageResponse),
("timetable-image", timetableImageResponse x),
("graph-fb",toResponse ""),
("post-fb",toResponse ""),
("test", getEmail),
("test-post", postToFacebook),
("post", postResponse),
("draw", drawResponse),                  
("about", aboutResponse),
("privacy" ,privacyResponse),
("static", serveDirectory),
("course", retrieveCourse),
("all-courses", allCourses),
("graphs", queryGraphs),
("course-info", courseInfo),
("depts", deptList),
("timesearch",searchResponse),
("calendar",calendarResponse),
("get-json-data",getGraphJSON),
("loading",loadingResponse),
("save-json", saveGraphJSON)]

Answer

jkeuhlen picture jkeuhlen · Jun 23, 2016

map is defined as:

map :: (a -> b) -> [a] -> [b]

This means it is a function that takes a function that goes from type a to type b and a list of type a, and then returns a list of type b. As pointed out by @pdexter and @karakfa in the comments, this is exactly what you need.

map f list

So what f do you need? Well, your list is a list of tuples and you want to apply a function to the first element to each tuple, so (exactly as @karakfa pointed out) all you need is

map (dir . fst) list

This composes the function fst with your custom dir function to give you a new function that will take the first element of a tuple and do whatever your dir function does to it. Then map applies that over the entire list.