Adding only unique elements to a list from another list - list

I am creating a service that returns lists of articles from an XML feed. I am trying to find a better way to update the list of articles currently stored in my program whenever the client code calls for an update.
I have a variable named articleHistory which is the list of articles I want to update. I have the new list of articles, aptly named newArticles, which my article retrieval function returns. There will be articles which are present in both lists. But the newArticles list will contain articles which are not in the articleHistory list. I am currently using a temporary variable, appending newArticles to articleHistory, and then returning that after calling the distinct method.
def updateArticleHistory: List[Article] = {
val newArticles = getArticles
val temp = newArticles ::: articleHistory
articleHistory = temp.distinct
}
Assume there is a case class name Article available. I feel there has to be a better way to do this, but I can't figure it out.

It seems like what you want is ListSet. A ListSet is a Set (since it only allows one of each element) but is maintains the insertion order. The one weird thing is that since it inserts elements at the head, the list is backwards.
import collection.immutable.ListSet
val a = ListSet.empty[Int]
val b = a ++ List(3,4,5) // ListSet(5, 4, 3)
val c = b ++ List(1,2,3,4,5,6) // ListSet(6, 2, 1, 5, 4, 3)
c.toList.reverse // List(3, 4, 5, 1, 2, 6)

I don't know, but why you can't do smth like this:
val lstA: List[Int] = List[Int](1, 2, 3, 4)
val lstB: List[Int] = List[Int](5, 6, 7, 1, 2)
println(lstA ::: lstB distinct)
>> List(1, 2, 3, 4, 5, 6, 7)
I think it's nice:)

Related

Pattern match against List 'init' and 'last' instead of 'head' and 'tail'

I know that it's possible to easily pattern match against the head (or an arbitrary number of initial elements) and tail of a List:
val items = List(1, 2, 3, 4)
val first :: rest = items
println(first, rest) // 1, List(2, 3, 4)
However, I would like to do it the other way - can you use a pattern to get the init and last of the list?
val items = List(1, 2, 3, 4)
val rest ??? last = items
println(rest, last) // List(1, 2, 3), 4
In JavaScript this would look like:
const [...init, last] = items
You can use the :+ custom extractor object.
So the code would look like this:
val rest :+ last = items
However, note that this is equally inefficient than doing:
val last :: rest = items.reverse
But, if you then need to decompose rest again, then reversing it first will be more efficient.
Finally, remember both are unsafe since they will throw in case the List is empty.
This should work:
val xs :+ x = items
Check out: https://www.scala-lang.org/files/archive/api/2.12.0/scala/collection/Seq.html#:+(elem:A):Seq[A]

what is dart equivalence function for a filtering a list?

what is dart equivalence function of filtering a list? The following java code contains boolean value argument to performs filtering on a list. how best can this be represented in dart?
public List<playlist> findVideos(Predicate<Playlist> filter) {
return videos.stream().filter(filter).collect(Collectors.toList());
}
Dart has where method for Iterable class.
For example:
final list = <int>[1, 2, 3, 4, 5, 6, 7, 8, 9];
print(list.where((i) => i > 4)); // prints [5, 6, 7, 8, 9]
Dart's collection-for and collection-if constructs allows you to build lists directly with expressions very similar to control flow statements. For example:
List<playlist> findVideos(bool Function(Playlist) filter) {
var filteredList = [
for (var playlist in videos.stream())
if (filter(playlist))
playlist,
];
// ...
}

What is the use of returning [...list] in Dart?

In Dart programming language, sometimes I see functions returning a list in pair of brackets with triple dots [...list]. For example:
class IntList {
List<int> _integerList = [1, 2, 3, 4, 5];
List<int> get integerList {
return [..._integerList];
}
}
So what is the difference between return integerList; and the above return statement?
Any help is really appreciated. Thank you.
For this particular case there is no difference. ... is the spread operator. This allows you to insert multiple elements into a collection.
For example:
var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2)
Output:
[0, 1, 2, 3]
So doing return [..._integerList]; is the exact same as return integerList;, other than that it creates a new list.
var list = [1, 2, 3];
print(list.hashCode);
print([...list].hashCode);
This code shows that they are different List objects when the spread operator is used because of the output of different hash codes.

How to add an element to List while making sure that list contains latest n elements in scala

In Scala, what is the best way to add an element to a list while making sure that the list always contains latest n elements.
So if list is (1, 2, 3, 4, 5) and n = 5, then adding 6 should result in (2, 3, 4, 5, 6).
One possible way could be:
list = list ::: List(6)
list = list.takeRight(5)
Are there any better ways? Also, is there a better data-structure for maintaining such frequently changing collection?
It sounds like a fixed size Circular Buffer would satisfy your need. I think apache commons provides some implementation.
A solution in scala using List could be:
scala> def dropHeadAndAddToList[T](obj: T, list: List[T]):List[T] = {
list.drop(1) :+ obj
}
dropHeadAndAddToList: [T](obj: T, list: List[T])List[T]
scala> val a = List(1,2,3,4,5)
a: List[Int] = List(1, 2, 3, 4, 5)
scala> dropHeadAndAddToList(6, a)
res0: List[Int] = List(2, 3, 4, 5, 6)

Creating lists and sets in Scala: What do I actually get?

If I create a Set in Scala using Set(1, 2, 3) I get an immutable.Set.
scala> val s = Set(1, 2, 3)
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
Q1: What kind of Set is this actually? Is it some hash-set? What is the complexity of look-ups for instance?
Q2: Where can I read up on this "set-creating" method? I thought that it was the apply method but the docs says "This method allows sets to be interpreted as predicates. It returns true, iff this set contains element elem."
Similarly, if I create a List using List(1, 2, 3), I get
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l.getClass
res13: java.lang.Class[_] = class scala.$colon$colon
Q3: Again, what do I get? In this case I can't even immediately tell if it's mutable or not, since it's not even part of the scala.collection-package. Why does this live in the scala package?
Q4: Where in the API can I read about this "list-creating" method?
Q1: In this specific case you get a Set3 which is an immutable set of exactly three arguments. Presumably it uses if-else if-else to check inclusion. If you create a set of more than 4 elements, you get an immutable hash set.
Q2: You need to look at the apply method of the object Set, not the class. The apply method of the Set class is what is called when you do someSet(something).
Q3: scala.:: is a non-empty immutable singly linked list (if you do List() without arguments, you get Nil which is an immutable empty list). It lives in the scala package because it is considered so basic that it belongs in the base package.
Q4: See Q2.
Just to add to sepp2k's excellent answer to Q3, where he says
It lives in the scala package because
it is considered so basic that it
belongs in the base package.
This applies to Scala 2.7
In Scala 2.8, the collections classes have been reorganized, and now the :: class lives in scala.collection.immutable, and the name scala.:: is a type alias for scala.collection.immutable.::.
Welcome to Scala version 2.8.0.RC5 (OpenJDK 64-Bit Server VM, Java 1.6.0_18).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l.getClass
res0: java.lang.Class[_] = class scala.collection.immutable.$colon$colon
scala> scala.::
res1: collection.immutable.::.type = scala.collection.immutable.$colon$colon$#6ce5d622
if you call getClass method on the
scala> val list = List(1,2,3,45)
list: List[Int] = List(1, 2, 3, 45)
scala> val seq = Seq(1,2,3,4,5)
seq: Seq[Int] = List(1, 2, 3, 4, 5)
scala> list.getClass
res13: Class[_ <: List[Int]] = class scala.collection.immutable.$colon$colon
scala> seq.getClass
res14: Class[_ <: Seq[Int]] = class scala.collection.immutable.$colon$colon
That’s because scala.collection.immutable.List is an abstract class, and it comes with two implementations: the scala.Nil class and scala.::. In Scala, :: is a valid identifier, and you could use it to name a class. Nil represents an empty list, and scala.:: represents any nonempty list.