用绝对值更新列表的值 [英] Update the values of a list with their absolute values

查看:91
本文介绍了用绝对值更新列表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手到Scala.

我正在尝试使此代码工作几个小时.打算用整数的绝对值更新List [Int](整数列表). 花了很长时间才弄清楚List是不可变的,因此发现ListBuffer可以作为救星,但最终我将其返回到List形式时遇到了一些问题.

I am trying to make this code to work for a few hours now . It is intended to update the List[Int](list of integers) with absolute values of the integers. Took a long time to figure out that List is immutable, so found that ListBuffer can be the saviour, but eventually in returning it back into the List form is seeing some issue i guess.

def f (arr:List[Int]) : List[Int] =
{
  val list = new scala.collection.mutable.ListBuffer[Int]();
  val len = arr.length;
  for ( i <- 0 to len)
  {
    if(arr(i) < 0)
    {

      list.append((-1)*arr(i)) ;
    }
    else
    {
      list.append(arr(i));
    }
  }

  return list.toList;

}

出现此错误:

java.lang.IndexOutOfBoundsException: 12
at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:52)
at scala.collection.immutable.List.apply(List.scala:84)
at Solution$.f(Solution.scala:7)
at Solution$delayedInit$body.apply(Solution.scala:23)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:7...

没有弄明白这里出了什么问题.

Not getting what's wrong here.

推荐答案

最好的方法是使用注释中建议的Scala函数,例如@senia.例如:

The best way is to use Scala functions like @senia suggested in comments. For example:

val res = list map math.abs

但是,如果要修复代码,只需将to替换为until.您因一个错误而下车:

But if you want to fix your code just replace to with until. You are getting off by one error:

def f (arr:List[Int]) : List[Int] =
{
val list = new scala.collection.mutable.ListBuffer[Int]();
val len = arr.length;
for ( i <- 0 until len)
{
    if(arr(i) < 0)
    {

        list.append((-1)*arr(i)) ;
    }
    else
    {
        list.append(arr(i));
    }
}

return list.toList;

}

这是untilto之间的区别:

1 to 3
// Range(1, 2, 3)

1 until 3
// Range(1, 2)

您还可以删除与if/else一起使用的return;甚至大括号{.

You can also remove return, ; and even braces { used with if/else.

这篇关于用绝对值更新列表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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