2

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)]
Mia.M
  • 97
  • 1
  • 1
  • 8
  • 4
    Do you know about `map` ? – pdexter Jun 23 '16 at 16:04
  • 2
    `map (dir . fst) data` – karakfa Jun 23 '16 at 16:04
  • 1
    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 Jun 23 '16 at 16:05
  • Thanks to everyone here! `map` is very useful! – Mia.M Jun 23 '16 at 16:44
  • As an exercise, you should solve this using both `map` and explicit recursion with pattern matching. `f [] = ... ; f ((x,y):rest) = ...` – chi Jun 23 '16 at 17:26

1 Answers1

6

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.

jkeuhlen
  • 4,401
  • 23
  • 36
  • a further question here: what if I want to apply map on a function that takes in two variables? For example, I have a function called `doubleUs` here, and `doubleUs = x*2 + y*2`. And x is from list [1,2,3], y is from list [2,3,4]. How can I achieve that? – Mia.M Jul 07 '16 at 18:49
  • That's been answered a few times on this site before. Take a look at [this question(http://stackoverflow.com/questions/9448570/using-map-with-two-lists-rather-than-one-can-you-nest) as an example. – jkeuhlen Jul 07 '16 at 18:51