简体   繁体   English

将函数映射到Haskell 2元素中的列表一次

[英]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: 我在Haskell尝试了一些问题(在Spoj ),我偶然发现了一些有输入形式的问题:

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 正如您所看到的,只能通过在输入上使用wordslines来解决这个问题,然后映射求解器函数以获得类似

[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. 所以我很高兴找到一个类似的map函数,它一次应用一个函数2参数。我一直无法在Hoogle上找到任何东西,但是编写这样的函数很容易,我正在寻找一个问题的更一般方法。或者,如果我的方法(坚持map )肯定是错误的,那么我也可以指出正确的方向。

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非常有用,它将一个函数映射到一个列表,一次只能处理两个参数:

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

Use chunksOf . 使用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. map是一个很好的方法,如果你的数据是这样的结构,你可能想稍微改变它以更好地适应语义。 One way to do that would be to "pair up" the result of lines so that you get [(line1, line2),(line3, line4),...] . 要做到这一点的方法之一将是“对了”的结果lines ,让你得到[(line1, line2),(line3, line4),...] The first argument of map will then be a function that works on these tuples. map的第一个参数将是一个适用于这些元组的函数。

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. 确切的解决方案取决于输入数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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