Scala:使用最后一个非空值填充列表中的空白 [英] Scala: Fill the gaps in a List with last non-empty value

查看:870
本文介绍了Scala:使用最后一个非空值填充列表中的空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

val arr = Array("a", "", "", "b", "c", "")

我正在寻找一种创建方法:

I am looking for a way to create:

Array("a", "a", "a", "b", "c", "c")


推荐答案

向左折叠:

(Array.empty[String] /: arr) {
    case (prev, "") => prev :+ prev.lastOption.getOrElse("");
    case (prev, l) => prev :+ l
}

> res01: Array[String] = Array(a, a, a, b, c, c)

这将通过添加 arr 元素或生成的列表最后一个来创建一个新数组,取决于源元素是否为空字符串。

This builds a new array from the previous by appending arr elements or the resulting list's last depending on whether the source element is the empty string or not.

也可以写成:

(Array.empty[String] /: arr) {
    case (Array(), l) => Array(l)
    case (prev, "") => prev :+ prev.last;
    case (prev, l) => prev :+ l
}

可以使用列表和前缀来优化:

It can be optimized by using lists and prepend:

{(List.empty[String] /: arr) {
    case (Nil, l) => l::Nil
    case (h::tail, "") => h::h::tail;
    case (prev, l) => l::prev
} reverse } toArray

如果你不喜欢符号版本的左折叠和右折叠方法。这里它有它的文本标识符:

In case you don't like the symbolic version of the fold left and fold right methods. Here it comes with its textual identifier:

arr.foldLeft(Array.empty[String]) {
    case (prev, "") => prev :+ prev.lastOption.getOrElse("");
    case (prev, l) => prev :+ l
}

arr.foldLeft(List.empty[String]) {
    case (Nil, l) => l::Nil
    case (h::tail, "") => h::h::tail;
    case (prev, l) => l::prev
}.reverse toArray

它完全相同的方法和实现,不同的名称。

Its exactly the same approach and implementation but with a different name.

这篇关于Scala:使用最后一个非空值填充列表中的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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