[英]How to apply a function on each element in a list in Haskell?
我在這里有一個元組列表,我想在每個元組的第一個元素上應用函數dir..
我怎樣才能做到這一點? 在此先多謝!
[ ("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)]
map
定義為:
map :: (a -> b) -> [a] -> [b]
這意味着它是一個函數,它接受從類型a到類型b的函數以及類型a的列表,然后返回類型b的列表。 正如@pdexter和@karakfa在評論中指出的,這正是您所需要的。
map f list
那你需要什么? 好吧,您的列表是一個元組列表,並且您想要對每個元組的第一個元素應用一個函數,因此(正好是@karakfa指出的)
map (dir . fst) list
這會將函數fst與您的自定義dir函數組合在一起,從而為您提供一個新函數,該函數將采用元組的第一個元素,並對dir函數執行的操作相同。 然后map將其應用於整個列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.