2
\$\begingroup\$

Can I reduce the loop inside my method with map or is there a shorter implementation of this code that's dropping elements in sequence?


// Method that drops one element in sequence
def drop_Val_In_List[String](ls: Seq[String], value: String): Seq[String] = {
 val index = ls.indexOf(value) //index is -1 if there is no matc
 if (index < 0) {
 ls
 } else if (index == 0) {
 ls.tail
 } else {
 // splitAt keeps the matching element in the second group
 val (a, b) = ls.splitAt(index)
 a ++ b.tail
 }
}
val KeepCols = Seq("id", "type", "month", "car", "road")
// Generalization of the above method to drop multiple elements
def drop_Val_List_In_List[String](ls: Seq[String], in_ls: Seq[String]): Seq[String] = {
 var tmp_ = ls
 //println(tmp.getClass)
 for(x <- in_ls ){ // should work without var x
 tmp_ = drop_Val_In_List(tmp_, x)
 }
 tmp_;
}
val tmp = drop_Val_List_In_List(KeepCols, List("id", "type", "month"))
```
Snowbody
8,66225 silver badges50 bronze badges
asked Oct 30, 2020 at 11:38
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to the Code Review site where we review working code and provide suggestions on how to improve that code. Code that is not working as expected is considered off-topic and the question may be closed by the community. This type of question is more appropriate on stack overflow, but please read their guidelines for asking a good question first. \$\endgroup\$ Commented Oct 30, 2020 at 12:21
  • \$\begingroup\$ Welcome to Code Review. It appears that you updated the code in revision 2 and removed the text about an error in revision 3. However, trying the code in multiple online tools shows there is still an error on that line that calls drop_Val_In_List() i.e.: type mismatch; found : java.lang.String; required: String(in method drop_Val_List_In_List) \$\endgroup\$ Commented Oct 30, 2020 at 15:58
  • 1
    \$\begingroup\$ I appreciate your observation. Now it should work \$\endgroup\$ Commented Oct 30, 2020 at 16:21

1 Answer 1

3
\$\begingroup\$

Follow the naming convention of the language

For scala, this is here. Spell methods and variables in lower camel case:

drop_Val_In_List
drop_Val_List_In_List
in_ls

Use the most appropriate data structure

To me, it seems like you want a set, not a sequence/list. Set also has the method you want:

val KeepCols = Set("id", "type", "month", "car", "road")
val tmp = KeepCols.diff(Set("id", "type", "month"))

If you don't want to use a set, Seq also has diff.

answered Oct 30, 2020 at 13:36
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.