6

I want to learn how to write for loop functions without declear "var" at the front of the code. For example, I want to remove duplicates in an interger Array. In C++/Java, I can do like that:

int removeDuplicate(vector<int> nums)
{
     vector<int> output
     Map<int,int> counter;
     for(i = 0; i < nums.size(); i++)
     {
         if(!counter.has_key(nums[i]))
         {
             counter[nums[i]]=1;  //add new key-value pair
             output.push_back(nums[i]);
         }
     }

     return output;
}

But in scala, how to use immutable variables to complete above task.

Do NOT use scala's internal functions, such as distinct. This question is about Scala implementation.

1
  • 1
    distinct is a method, not a function, so I guess that means you are allowed to use it? Note that in your C++ example, size(), has_key(), push_back(), operator[], etc. are also "internal functions", yet you seem to have no trouble using them, so what makes those "internal functions" different from other "internal functions"? And what is an "internal function" anyway? Commented Sep 9, 2017 at 9:39

3 Answers 3

15

In Scala to avoid using vars in this case you can use recursion or foldLeft or foldRight:

def distinct[A](list:List[A]):List[A] = 
  list.foldLeft(List[A]()) {
    case (acc, item) if acc.contains(item) => acc
    case (acc, item) => item::acc
  }   
Sign up to request clarification or add additional context in comments.

2 Comments

is this gonna reverse the list?
using foldLeft with appending to head reverses the list
6

Scala provides lots of library functions. Like, there is distinct function. You can directly call it.

scala> val array = Array(1,2,3,2,1,4)
array: Array[Int] = Array(1, 2, 3, 2, 1, 4)
scala> array.distinct
res0: Array[Int] = Array(1, 2, 3, 4)

And if there is no library function, we prefer to write code using recursion mostly tail recursion so that we can maintain immutability. Or you may convert array into Set which will remove duplicates and then convert set into array again to get desired result.

scala> array.toSet.toArray
res3: Array[Int] = Array(1, 2, 3, 4)

In scala, list is preferred over array as array is mutable collection in scala and list is immutable. So prefer to use it.

1 Comment

Worth noting; .toSet.toArray will not maintain element order.
0

There are several ways to do this in Scala (without distinct). All of these alternatives use immutable variables:

Using groupBy:

val x: Seq[Int] = Seq(1,2,3,3,4,5,6,6)
val unique: Seq[Int] = x.groupBy(identity).keys.toSeq

Using toSet:

val x: Seq[Int] = Seq(1,2,3,3,4,5,6,6)
val unique: Seq[Int] = x.toSet.toSeq

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.