Scala 中的尾递归用例解决方案 [英] Tail Recursion Use Case Solution in Scala

查看:49
本文介绍了Scala 中的尾递归用例解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用尾递归解决问题.用例是:

I am trying to solve a problem using tail recursion. The use case is:

我有文件夹列表,每个文件夹都有文件列表,每个文件都有几条记录.我想对记录进行一些转换并将它们批量写入 kinesis.

val listOfFolders = Folder1(File1(RF11, RF12, RF13), File2(RF21,RF22))

我想在 kinesis 中一次写两个记录.到目前为止,我已经尝试过:

I want to write let's say two records at a time in kinesis. So far I have tried:

listOfFolders.map { folder =>
    val files = fetchAllFilesFromFolder(folder)
    if (files.nonEmpty) {
      sendBatch(files, Seq.empty[(ByteBuffer, String)], 2)
    } else {
      logger.info(s"No files are present in folder")
    }
  }

  @scala.annotation.tailrec
  def sendBatch(
    files: Seq[Files],
    buffer: Seq[(ByteBuffer, String)],
    numberOfRecordsToSend: Int
  ): Unit =
    files match {
      case Nil => {
        if (buffer.nonEmpty) {
          sendToKinesis(streamName, buffer) map { putDataResult =>
            val putDataList = putDataResult.getRecords.asScala.toList
            logger.info(
              s"Successfully Sent"
            )
          }
        } else {
          logger.info(s"Successfully sent")
        }
      }
      case head :: tail => {
        val fileData = readFileData()
        val byteData: Seq[(ByteBuffer, String)] = transformDataAndConvertToByteBuffer(fileData)

        val currentBatch = buffer ++ byteData
        if (currentBatch.size >= numberOfRecordsToSend) {
          sendToKinesis(streamName, buffer)  map { putRecordRes =>
            val putDataList = putRecordRes.getRecords.asScala.toList
            logger.info(
              s"Sent successfully" 
            )
          }
          sendBatch(tail, Seq.empty[(ByteBuffer, String)], 2)
        } else {
          sendBatch(tail, currentBatch, 2)
        }
      }
    }

sendToKinesis 使用 KCL putRecords.

sendToKinesis uses KCL putRecords.

上面代码的问题是:

  • 从一个文件中读取所有数据.所以如果文件有 5 条记录将发送kinesis 有 5 条记录,但批量大小为 2.

  • Reads all the data from one file. So if file has 5 records will send 5 records to kinesis but the batch size is 2.

无法从地图调用尾递归方法.

Can't call the tail recursive method from map.

如果 - 如果文件 1 有 3 条记录,则应注意发送 2 条记录将 RF11、RF12 一起记录,然后将 RF13、RF21 一起记录,最后RF22.

Also to be taken care if - If file1 has 3 records it should send 2 records RF11, RF12 together and then RF13,RF21 together and at last RF22.

我不想在我的代码中使用任何 var.可以用tail rec解决吗?

I do not want to use any var in my code. Can it be solved using the tail rec?

推荐答案

你有两个子问题

  1. 如何发送固定大小的批次

@scala.annotation.tailrec
def sendBatch(file: Option[File], buffer: Seq[(ByteBuffer, String)], numbersOfRecrodsToSend: Int): Seq[(ByteBuffer, String)] = {
  if (buffer.length < numbersOfRecrodsToSend) {
    // case 1: too few records to be sent 
    file match {
      // case 1.1: file was not yet read
      case Some(f) => sendBatch(None, buffer ++ getByteData(f), numbersOfRecrodsToSend)
      // case 1.2: too few records, file was already read, return leftover records
      case None => buffer
    }
  } else {
    // case 2: we can send numbersOfRecrodsToSend to Kinesis
    val (toSend, newBuffer) = buffer.splitAt(numbersOfRecrodsToSend)
    sendToKinesis(streamName, toSend)
    sendBatch(file, newBuffer, numbersOfRecrodsToSend)
  }
}

  1. 如何遍历列表并发送固定大小的批次

// start with empty list of files to send and for each folder
// add it's files to the buffer and send as many records as you can
// the leftover is going to be passed to next iteration for both files and directories
val partial = listOfFolders.foldLeft(Seq.empty[(ByteBuffer, String)]) { case (acc, folder) =>
  fetchAllFilesFromFolder(folder).foldLeft(acc) { case (acc2, file) => 
    sendBatch(Some(file), acc2, numbersOfRecrodsToSend)
  }
}

// if any records have left - send them too
if (partial.nonEmpty) {
  sendToKinesis(streamName, partial)
}

<小时>

希望你有这个想法.


Hopefully you got the idea.

这篇关于Scala 中的尾递归用例解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆