scala 在元组列表上使用 map() 时的详细表示法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9979585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:03:28  来源:igfitidea点击:

Verbose notation when using map() on Lists of tuples

listscala

提问by flend

I like to have my code quite naively readable.

我喜欢让我的代码非常简单易读。

If I set up a simple list of tuples:

如果我设置一个简单的元组列表:

scala> val a = List(6, 8, 10)
a: List[Int] = List(6, 8, 10)

scala> val b = a zipWithIndex
b: List[(Int, Int)] = List((6,0), (8,1), (10,2))

I'd like to map() on the List, but I find the ._1 ._2 syntax a bit hard-to-read:

我想在列表上 map() ,但我发现 ._1 ._2 语法有点难以阅读:

scala> val c = b map ( a => if(a._1 > 8) a._1 else a._2 )           
c: List[Int] = List(0, 1, 10)

To 'name' the tuple, I've used:

为了“命名”元组,我使用了:

scala> val c = b map ( { case (num, i) => if(num > 8) num else i } )
c: List[Int] = List(0, 1, 10)

Two questions:

两个问题:

1) Is there a more concise way to name the tuple members?

1)有没有更简洁的方法来命名元组成员?

2) Is there a considerable performance hit for my version above (it is used in moderately performance-critical code).

2)我上面的版本是否有相当大的性能损失(它用于中等性能关键代码)。

Thanks.

谢谢。

采纳答案by Luigi Plinge

b map Function.tupled((num, i) => if(num > 8) num else i)

avoids pattern matching and for-expressions so should be reasonably performant. I'd normally just use caseas you did though.

避免模​​式匹配和 for 表达式,因此应该具有合理的性能。我通常只是case像你一样使用。

回答by Paolo Falabella

In this case you might find the equivalent for-comprehension syntax more readable, but it's really a matter of taste...

在这种情况下,您可能会发现等效的 for-comprehension 语法更具可读性,但这确实是一个品味问题......

for {(num, i) <- b} yield if(num >8) num else i

FWIW, I've tried benchmarking the map with and without pattern matching and I got pretty much the same execution time.

FWIW,我试过在使用和不使用模式匹配的情况下对地图进行基准测试,我得到的执行时间几乎相同。

Code I've used:

我用过的代码:

object bench extends scala.testing.Benchmark {
    var b:List[(Int, Int)] = _

    override def setUp {
        val a = (1000000 to 2000000).toList
        b = a zipWithIndex
    }

    def run = b map ( a => if(a._1 > 8) a._1 else a._2 )
 }

I've also created another application with a bench1object which has only the version of map with the pattern matching instead of the ._1and ._2. Results on my oldish netbook (scala 2.9.1, xubuntu 11.10):

我还创建了另一个具有bench1对象的应用程序,该对象只有具有模式匹配的 map 版本而不是._1and ._2。我的旧上网本(scala 2.9.1,xubuntu 11.10)上的结果:

$ scala bench 10 
bench$   750    758 731 721 733 736 725 743 735 736
$ scala bench1 10
bench1$  774    772 740 724 745 730 711 739 740 740