将数组引用传递给scala中的函数

时间:2014-02-13 13:35:07

标签: arrays scala reference

如何传递对数组的引用以在scala中起作用。

例如以下是c / c ++中的函数

如何在scala中编写数组ref的代码?

int RMQUtil(int *st, int ss, int se, int qs, int qe, int index)
{
// If segment of this node is a part of given range, then return the
// min of the segment
if (qs <= ss && qe >= se)
    return st[index];

// If segment of this node is outside the given range
if (se < qs || ss > qe)
    return INT_MAX;

// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1),
              RMQUtil(st, mid+1, se, qs, qe, 2*index+2));
}

2 个答案:

答案 0 :(得分:3)

对于方法的多个参数,请考虑

case class Params(ss: Int, se: Int, qs: Int, qe: Int, index: Int)

Scala重新编码上面提到的方法,

def RMQUtil(st: Array[Int], p: Params): Int = {
  if (p.qs <= p.ss && p.qe >= p.se) 
    st(index)
  else if (p.se < p.qs || p.ss > p.qe)
    Int.MaxValue
  else {
    val mid: Int = getMid(ss, se)
    Math.min( RMQUtil(st, Params(p.ss, mid, p.qs, p.qe, 2*index+1)),
              RMQUtil(st, Params(mid+1, p.se, p.qs, p.qe, 2*index+2)))
  }
}

答案 1 :(得分:1)

这样的事情应该有效:

def RMQUtil(st: Array[Int], ss: Int, se: Int, qs: Int, qe: Int, index: Int): Int = {
  if (qs <= ss && qe >= se)
    return st(index)
  if (se < qs || ss > qe)
    return Int.MaxValue

  val mid = getMid(ss, se) // I assume this is something like (ss + se) / 2
  Math.min(RMQUtil(st, ss, mid, qs, qe, 2*index+1), RMQUtil(st, mid+1, se, qs, qe, 2*index+2))
}