简体   繁体   中英

mapping a function to a list in Haskell 2 elements a time

I am trying a few problems (at Spoj ) in Haskell and I have stumbled on quite a few which have input of the form:

testcase_1
testcase_1_continued
testcase_2 
testcase_2_continued

or

testcase_1 testcase_1_continued
...

As you can see, one cannot solve this by just using words or lines on the input and then mapping the solver function to get something like

[solver test1, solver test2, ...]

One should use a function with two arguements, which are two list elements, one after the other, and get:

[solver test1 test1continued, solver test2 test2continued, ...]

So I would be pleased to find an analogous function to map which applies a function 2 arguments at a time.I have not been able to find anything on Hoogle, and however easy it would be to write such a function, I am looking for a more general approach to the problem.Or, if my approach(of insisting on map ) is definitely wrong, one could also point me to the right direction.

Edit:

I actually found it really useful to implement a function map2 which maps a function to a list, only it works two arguments a time:

map2 f [a,b,c,d] ==> [f a b, f c d]

Use chunksOf .

> map (\[x, y] -> x + y) . chunksOf 2 $ [1..30]
[3,7,11,15,19,23,27,31,35,39,43,47,51,55,59]

map is a great way to go, and if your data is structured like that, you might want to alter it slightly to fit the semantics better. One way to do that would be to "pair up" the result of lines so that you get [(line1, line2),(line3, line4),...] . The first argument of map will then be a function that works on these tuples.

Edit: To expand on that, the general approach is then to read the input, format it into a semantically meaningful format, then either map or fold your solving function over the result. The exact solution depends on the input data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM