\$\begingroup\$
\$\endgroup\$
3
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"))
```
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
lang-scala
drop_Val_In_List()
i.e.:type mismatch; found : java.lang.String; required: String(in method drop_Val_List_In_List)
\$\endgroup\$