提取元组和音频列表中的各个值使用模式匹配

时间:2018-03-29 18:28:34

标签: scala tuples

这是我的代码

localStorage

如您所见,我能够将元组提取到Sub FindAndReplaceText() Dim FileName As String Dim FolderPath As String Dim FSO As Object Dim I As Integer Dim SearchForWords As Variant Dim SubstituteWords As Variant Dim Text As String Dim TextFile As Object 'Change these arrays to word you want to find and replace SearchForWords = Array("string1", "string2", "string3") SubstituteWords = Array("string100", "string200", "string300") 'Change the folder path to where your text files are. FolderPath = "C:\your_path_here\" Set FSO = CreateObject("Scripting.FileSystemObject") FolderPath = IIf(Right(FolderPath, 1) <> "\", FolderPath & "\", FolderPath) FileName = Dir(FolderPath & "\*.txt") Do While FileName <> "" FileSpec = FolderPath & FileName 'Read all the file's text into a string variable. Set TextFile = FSO.OpenTextFile(FileSpec, 1, False) Text = TextFile.ReadAll TextFile.Close 'Scan the string for words to replace and write the string back to the file. Set TextFile = FSO.OpenTextFile(FileSpec, 2, False) For I = 0 To UBound(SearchForWords) Debug.Print Text Replace Text, SearchForWords(I), SubstituteWords(I) Debug.Print Text Next I TextFile.Write Text TextFile.Close FileName = Dir() Loop End Sub @ val lst = List((12, "aug", 2016), (13, "jun", 2016)) lst: List[(Int, String, Int)] = List((12, "aug", 2016), (13, "jun", 2016)) @ lst.foreach { case (day, month, year) => println(s"Tpl is ($day, $month, $year)") } Tpl is (12, aug, 2016) Tpl is (13, jun, 2016) &amp; day。但对我来说问题是当我想要打印元组时,我需要连接值。是否有一种方法可以使用模式匹配来提取完整​​的元组(以及值)。我需要这样的东西(当然这不起作用

month

我知道可以这样做(如下所示);但我试图避免额外的代码和额外的缩进级别

year

2 个答案:

答案 0 :(得分:3)

  

这个答案与另一个答案重复:   Scala pattern matching referencing

:替换为@

case tpl @ (day, month, year) =>
  println(s"Tpl is $tpl = ($day, $month, $year)")

这叫做pattern binder (link to specification)

答案 1 :(得分:1)

访问元组字段的另一种方法是Andreys代码,它没有真正显示它,将是:

lst.foreach {case tpl => println (s"Tupel ${tpl} is ${tpl._1} ${tpl._2} ${tpl._3}")}
Tupel (12,aug,2016) is 12 aug 2016
Tupel (13,jun,2016) is 13 jun 2016