How should I remove the first occurrence of an object from a list in Scala? -


what best way remove first occurrence of object list in scala?

coming java, i'm accustomed having list.remove(object o) method removes first occurrence of element list. i'm working in scala, expect method return new immutable list instead of mutating given list. might expect remove() method take predicate instead of object. taken together, expect find method this:

/**  * removes first element of given list matches given  * predicate, if any.  remove specific object <code>x</code>  * list, use <code>(_ == x)</code> predicate.  *  * @param toremove  *          predicate indicating element remove  * @return new list selected object removed, or same  *         list if no objects satisfy given predicate  */ def removefirst(toremove: e => boolean): list[e] 

of course, can implement method myself several different ways, none of them jump out @ me being best. rather not convert list java list (or scala mutable list) , again, although work. use list.indexwhere(p: (a) ⇒ boolean):

def removefirst[e](list: list[e], toremove: (e) => boolean): list[e] = {   val = list.indexwhere(toremove)   if (i == -1)     list   else     list.slice(0, i) ++ list.slice(i+1, list.size) } 

however, using indices linked lists not efficient way go.

i can write more efficient method this:

def removefirst[t](list: list[t], toremove: (t) => boolean): list[t] = {   def search(toprocess: list[t], processed: list[t]): list[t] =     toprocess match {       case nil => list       case head :: tail =>         if (toremove(head))           processed.reverse ++ tail         else           search(tail, head :: processed)     }   search(list, nil) } 

still, that's not succinct. seems strange there's not existing method let me efficiently , succinctly. so, missing something, or last solution gets?

you can clean code bit span.

scala> def removefirst[t](list: list[t])(pred: (t) => boolean): list[t] = {      |   val (before, atandafter) = list span (x => !pred(x))      |   before ::: atandafter.drop(1)      | } removefirst: [t](list: list[t])(pred: t => boolean)list[t]  scala> removefirst(list(1, 2, 3, 4, 3, 4)) { _ == 3 } res1: list[int] = list(1, 2, 4, 3, 4) 

the scala collections api overview great place learn of lesser known methods.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -