1
votes

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)]
1
Do you know about map ?pdexter
map (dir . fst) datakarakfa
Do you want to pull out the data, apply it, and return that list, or apply in place, returning the new value in the fst position, the original value in the snd position? I'd recommend map for the former, lenses for the latter.jamshidh
Thanks to everyone here! map is very useful!Mia.M
As an exercise, you should solve this using both map and explicit recursion with pattern matching. f [] = ... ; f ((x,y):rest) = ...chi

1 Answers

5
votes

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.