【问题标题】:Create a Seq of Elements based on Increment in Scala在 Scala 中基于增量创建元素序列
【发布时间】:2021-12-25 02:59:16
【问题描述】:

我需要生成具有特定开始和结束以及给定增量的特定数字类型的元素序列。这是我想出的:

import java.text.DecimalFormat

  def round(elem: Double): Double = {
    val df2 = new DecimalFormat("###.##")
    df2.format(elem).toDouble
  }

  def arrange(start: Double, end: Double, increment: Double): Seq[Double] = {
    @scala.annotation.tailrec
    def recurse(acc: Seq[Double], start: Double, end: Double): Seq[Double] = {
      if (start >= end) acc
      else recurse(acc :+ round(start + increment), round(start + increment), end)
    }
    recurse(Seq.empty[Double], start, end)
  }

  arrange(0.0, 0.55, 0.05) foreach println

这按预期工作,并给我以下结果:

0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55

但是,我想看看我是否可以使这个通用化,以便相同的函数适用于 Int、Long、Float。有没有办法简化这个?

【问题讨论】:

  • 是的,使用Numeric (这是一个typeclas。 - 顺便说一句,您可能想要使用 List 并添加 (最后带有 reverse 或使用 Vector;因为该代码可能效率极低。 - PS:在你不知道的情况下,stdlib 已经有了这样的功能;但我想这只是学习语言的练习。
  • 那是什么函数?
  • List.range - 其实你可以用任何集合替换List

标签: scala generics


【解决方案1】:

遇到了这个更简单的版本:

@ BigDecimal(0.0) to BigDecimal(0.5) by BigDecimal(0.05) 
res23: collection.immutable.NumericRange.Inclusive[BigDecimal] = NumericRange(0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50)

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 2015-10-26
    • 2018-05-10
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多