【问题标题】:Scala function that accepts array argument and returns a mutated array接受数组参数并返回变异数组的 Scala 函数
【发布时间】:2019-07-28 11:15:42
【问题描述】:

我想找出接受数组(或列表)并附加到数据结构的最实用的方法。然后最后返回新的数据结构。

类似这样的:

 def template(array: Array[String]): Array[Nothing] = {
  val staging_path = "s3//clone-staging/"
  var path_list = Array()
  //iterate through each of the items in the array and append to the new string.
  for(outputString <- array){
    var new_path = staging_path.toString + outputString
    println(new_path)
    //path_list I thought would add these new staging_path to the array
    path_list +: new_path

  }
 path_list(4)
 }

但是,调用数据结构的单个索引作为检查存在性的一种简陋方式,path_list(4) 返回一个 Out of Bounds。

谢谢。

【问题讨论】:

  • 我不确定path_list(4) 在那里做什么,但更惯用的解决方案是def template(values: List[String]) = values.map("s3//clone-staging" + _)
  • 只是试图从新的数据结构中返回一个索引来检查它是否存在。

标签: arrays scala list string-interpolation


【解决方案1】:

我想你只想在这里使用map

val staging_path = "s3//clone-staging/"
val dirs = Array("one", "two", "three", "four", "five")
val paths = dirs.map(dir => staging_path + dir)
println(paths)
// result: paths: Array[String] = Array(s3//clone-staging/one, s3//clone-staging/two, s3//clone-staging/three, s3//clone-staging/four, s3//clone-staging/five)
println(paths.length)
// result: 5

在函数式编程领域,您通常会尽量避免突变。相反,将其视为将输入数组转换为新数组。

【讨论】:

  • 通过创建本地 var path_list = Array() 来避免数据结构的原始突变是我的尝试
  • @tjmorri7 如果这解决了您的问题,请考虑接受此答案。如果没有,无论出于何种原因,请留下评论,解释为什么没有,以便可以改进答案。 - 看看What should I do when someone answers my question?
猜你喜欢
  • 2018-09-19
  • 2015-02-10
  • 2015-10-20
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多