如果迭代需要某种状态,如何以函数方式解析文件

时间:2014-10-16 13:40:11

标签: scala functional-programming

我有一个txt文件,其中包含由“first:”,“second:”和“third:”分隔的3个部分,这三个部分将被解析为case类Command。

文件格式:

first:
blablabla
blablabla
blablabla

second:
second details blablabla

third:
third details blablabla

案例类命令

case class Command(first: Array[String],
                   second: Array[String],
                   third: Array[String])

当我使用scalaz流迭代它时,我需要实现命令式代码和可变数据来在map方法中处理它。另外,我需要一个状态值,它可以告诉迭代器哪一行应该放入哪个ListBuffer。

val firstListBuffer = new ListBuffer[String]
val secondListBuffer = new ListBuffer[String]
val thirdListBuffer = new ListBuffer[String]

var parsingState = ""

io.linesR("testdata/fahrenheit.txt")
    .filter(s => !s.trim.isEmpty)
    .map(t => {
   //if it is first, parsingState = "first"
   //if parsingState = "first", firstListBuffer += t
   //if it is second, parsingState = "second"
   //if parsingState = "second", secondListBuffer += t
   //if it is third, parsingState = "third"
   //if parsingState = "third", thirdListBuffer += t
})

我只是想知道如何重构这个更实用的功能呢?

非常感谢提前

1 个答案:

答案 0 :(得分:-1)

abstract class ParsingState
case class First extends ParsingState
case class Second extends ParsingState
case class Third extends ParsingState
case class Command(first:String, second:String, third:String) 

def read(fileName:scala.io.Source):Command = { 
@tailrec
def helper(c:Command) = { 
  val p:ParsingState = //read heading, perform custom logic to assign the correct case class
  val newStrings:String = //read strings after heading, until we hit a new heading, need to return if EOF is hit
  p match { 
    case First => helper(Command(c.first + newStrings,c.second,c.third))
    case Second => helper(Command(c.first,c.second + newStrings, c.third))
    case Third => helper(Command(c.first,c.second,c.third + newStrings))
  } 
}    
helper(Command("","",""))
} 

注意:

我没有通过scalac运行它,我在Stackoverflow文本框内编码。我鼓励其他人使用这些代码并使其更好地作为解决方案,因为它不完整,我现在无法访问Scala编译器。这个解决方案虽然有一个功能范例。