score:3
you can avoid .zipwithindex()
by using .indexwhere()
.
to improve complexity, use vector
so that l(idx)
becomes effectively constant time.
val l = vector(1,2,3)
val idx = l.indexwhere(predicate)
val updateditem = updating(l(idx))
l.updated(idx, updateditem)
reason for using scala.collection.immutable.vector
rather than list
:
scala's list is a linked list, which means data are access in o(n) time. scala's vector is indexed, meaning data can be read from any point in effectively constant time.
you may also consider mutable collections if you're modifying just one element in a very large collection.
https://docs.scala-lang.org/overviews/collections/performance-characteristics.html
score:3
i don't know any way to make this in one pass of the collection without using a mutable variable. with two passes you can do it using foldleft
as in:
def updatefirst[a](list:list[a])(predicate:a => boolean, newvalue:a):list[a] = {
list.foldleft((list.empty[a], predicate))((acc, it) => {acc match {
case (nl,pr) => if (pr(it)) (newvalue::nl, _ => false) else (it::nl, pr)
}})._1.reverse
}
the idea is that foldleft
allows passing additional data through iteration. in this particular implementation i change the predicate to the fixed one that always returns false
. unfortunately you can't build a list
from the head in an efficient way so this requires another pass for reverse
.
i believe it is obvious how to do it using a combination of map
and var
note: performance of the list.map
is the same as of a single pass over the list only because internally the standard library is mutable. particularly the cons class ::
is declared as
final case class ::[b](override val head: b, private[scala] var tl: list[b]) extends list[b] {
so tl
is actually a var
and this is exploited by the map
implementation to build a list from the head in an efficient way. the field is private[scala]
so you can't use the same trick from outside of the standard library. unfortunately i don't see any other api call that allows to use this feature to reduce the complexity of your problem to a single pass.
Source: stackoverflow.com
Related Query
- Scala: Find and update one element in a list
- How to find a matching element in a list and map it in as an Scala API method?
- scala list counting element and find indices from other list
- How to find an element in a list based on a condition and return some data associated with that element in Scala
- Scala - create a new list and update particular element from existing list
- How can I idiomatically "remove" a single element from a list in Scala and close the gap?
- Remove one element from Scala List
- Apply function to one element only in list or array in Scala
- Scala grouping list into list tuples with one shared element
- scala sort list and get nth element
- Scala find element in nested List
- Scala - Find the exact index of the current element of a List
- scala - Find a pair in a list only with first element value
- Combine one List element with second list list in scala
- Find an element in a list in Scala
- finding the count of times element of one list is greater than the element of another list in scala
- Scala combine separate List[Map[String,Any]] into one list and concat Maps
- Iterating through Seq in Scala and find an element who satisfies the condition
- Deleting an element from a List in Scala using a loop and only a loop
- Scala - Find duplicates in list using pattern matching and recursion
- how can I write a function in scala called Order that takes one arguement: a list of Ints. And returns the same List of Ints from least to greatest
- Update dataset in spark-shell by breaking one element into multiple parts and inserting a row for each part
- How to get the current and next element of List of list of options in scala
- Scala -- List into List of Count and List of Element
- Scala - find maximum and sum of values in list of custom objects
- Find the proper first item in a list by checking it only one time, and return the checking result
- Scala - Creating a new list by combining the contents of one list and the hierarchy of another
- apply multiple filter conditions and produce only one element from a list
- how to pivot a table represented as scala List of Maps by taking one column and converting it to row?
- Scala [Functional]: Find the actual indices of an element within a list that may be repeated
More Query from same tag
- Return a child class from apply method of base trait
- Need held with scala compile time error when defining a lagom service implementation
- What is the idiomatic scala way to add more details to the thrown exceptions wrapped in Try instances
- Scala compiler reports type mismatch for closure
- Refreshing SBT project in Intellij Idea switches Java to 7
- Scalatest provide position different file for assertion
- In Scala, create a nested HashMap of length N given a list of length N
- Does Scala have an equivalent to Haskell's Prelude.show?
- How to use pattern matching in this if/else?
- Serialisation of Java and Scala objects with Scalatra
- spark: explanation of Row getDouble method
- Noise-free JSON processing with Scala
- PlayFramework - FakeRequest to upload file
- Scala factory pattern improve design
- How to run sbt-revolver with a Scala project?
- Scala - Can implicitNotFound annotation be applied at the method level?
- Verifying that generic type argument conforms to 2 unrelated types
- Fixing case object identity / pattern matching under serialization
- Spark/Scala Error - printing out Confusion Matrix for Logistic Regression
- [Exception: DB plugin is not registered.]
- Why parentheses around int on a scala method invocation
- how to ignore Play Framework WS SSL certs without making my entire application insecure?
- How to make ProGuard keep entire (whole) classes (with fields and methods) without using "-keep"
- Scala: difference of two sets by key
- Cannot Find GeneratorDrivenPropertyChecks Trait
- Scala sort string based on length of the tokens
- How does the scala compiler locate the positions for variance annotation
- Sequential scenarios each with a different protocol
- Handle Akka actor bounded mailbox MessageQueueAppendFailedException
- How to navigate up inside a HUET Zipper