gpt4 book ai didi

scala - Scala 中模拟/替换重复操作的一元加法的惯用方式

转载 作者:行者123 更新时间:2023-12-02 16:17:54 24 4
gpt4 key购买 nike

在支持一元加法的语言中,以及在对类似数组的结构中的顺序项执行一长串操作的情况下,我可能会创建一个简单的计数器“int counter= 0;”并执行以下操作:

someOperation(array[counter++]);
nextOperation(array[counter++]);
subsequentOperation(array[counter++]);
.. etc

scala 中实现类似行为的惯用方法是什么 - 即避免需要硬编码的输入数组索引?下面是一个具体示例:一个简单的记录解析器方法,它将制表符分隔的调用详细信息转换为 Call 对象。由于不知道有什么更好的方法,我做了一件丑陋的事情:放入一个 AtomicInteger。但是什么是可以接受的方法呢?

Note: we can not simply do a collective operation here because some of the columns require ".toInt" processing and others do not.

  def parseStringToCall(text: String) = {
val toks = text.split('\t')
val ix = new AtomicInteger(0)
new CallUpdate(
toks(ix.getAndIncrement), // callDate
toks(ix.getAndIncrement), // calledNumber
toks(ix.getAndIncrement), // callingNumbe
toks(ix.getAndIncrement), // cellTowersVi
toks(ix.getAndIncrement), // direction
toks(ix.getAndIncrement), // iMSI
toks(ix.getAndIncrement), // manufacturer
toks(ix.getAndIncrement), // phoneType
toks(ix.getAndIncrement), // reasonforDro
toks(ix.getAndIncrement).toInt, // weeknum
toks(ix.getAndIncrement), // firstCellTow
toks(ix.getAndIncrement), // lastCellTowe
toks(ix.getAndIncrement).toInt, // calls
toks(ix.getAndIncrement), // distinctCell
toks(ix.getAndIncrement), // droppedCall
toks(ix.getAndIncrement).toInt, // handovers
toks(ix.getAndIncrement).toInt, // setupTime
toks(ix.getAndIncrement).toInt // talkTime
)

最佳答案

你正在迫切地解决这个问题。惯用的 Scala 更多的是关于函数式编程。您必须习惯将函数视为值并利用这种力量。

您的问题可以通过如下方式解决:

toks
// Get a lazy wrapper around `toks`, so that all the subsequent
// operations will be done in just a single traversal:
.view
// Pair each item of `toks` up with an according operation:
.zip(List(someOperation(_), nextOperation(_), subsequentOperation(_)))
// Traverse thru those pairs, applying the operations:
.foreach{ case (t, f) => f(t) }

必须注意的是,操作的类型应为String => Unit

关于scala - Scala 中模拟/替换重复操作的一元加法的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23895762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com