RemoveAt not found in list kotlin? [duplicate] - list

This question already has answers here:
Kotlin's List missing "add", "remove", Map missing "put", etc?
(10 answers)
Closed 2 years ago.
I have a list whose value is filled from API
var dataList: List<Data?>? = null
I need to remove the element from 0th index
while in java I could use
dataList.removeAt(0)
But I don't see the function in kotlin

List supports only read-only access while MutableList supports adding and removing elements.
so var dataList: MutableList<Data?>? = null
will give you the option to remove an element.

This is because unlike java List is immutable in Kotlin. That means you can't modify after declaring it. To get functionalities like add,remove you can declare a mutable list in Kotlin like this:
val mutableList = mutableListOf<String>()
mutableList.add("Some data")
mutableList.removeAt(0)

You can't remove an item from a List. Nor can you add an item, nor change one. That's because List is a read-only interface!
If the list is mutable, you could instead have a MutableList reference to it. MutableList is a subinterface that adds all the methods for adding, changing, and removing items.

Related

Need the original length of a list as a "variable" in Haskell, but it keeps changing with recursion [duplicate]

This question already has an answer here:
How to store value of function call to a variable
(1 answer)
Closed 1 year ago.
I have a function in Haskell where I need the original length of a list to act as a static variable would in C, i.e. the length of the list when I first take it in is the value I need.
I'm recursively altering the list (namely via drop) as this is necessary for the function to work in the first place, but this of course makes the length of the list update as well and I'm not sure how I can access the original length of the list as it was when I took it in.
There seems to be an issue with the scope of my function and that I need to alter the scope of this value that I desire such that it does not change with the recursion on the list. I'm not sure exactly what the ideal way to go about retaining the original length of the list would be.
If you want a value then keep that variable around. This is often achieved using a helper function:
myfunction xs = helper xs
where
len = length xs
helper [] = 0
helper ys = len + helper (drop 1 ys)

in dart, which is better List.generate or List.of or List.from [duplicate]

This question already has answers here:
In Dart, what's the difference between List.from and .of, and between Map.from and .of?
(3 answers)
Closed 10 months ago.
in Dart Documentation we have three iterable options to choose from to create lists .which one is best suited for what purpose and which is more effiecient for what purpose?
Basically, you should never use any of those constructors.
Each has its use, but most of those uses can be written using list literals now.
The List.generate is a counterpart to List.filled. The latter creates a list filled with the same value in each slot, the former allows you to compute a new value for each slot.
With collection-for, I'd probably write:
var newList = [for (var i = 0; i < 10; i++) compute(i)];
instead of
var newList = List.generate(10, compute);
(even more so if I can inline the compute function).
The one case where generate makes sense is to create a fixed-length list. The literal cannot do that.
I'd also say that you should never use List.of(something).
Use something.toList() or [...something] instead. If you need to up-cast, say create a List<num> from an Iterable<int>, you can do <num>[...something], but you can't use toList. If you need to make a fixed-length List<num>, ... then I think List<num>.of(something, growable: false) is actually the simplest solution.
The only reason to use List.from is when the original iterable does not have as tight a type as needed. If you know that your Iterable<num> contains only integers, you might want to do List<int>.from(iterable). You can also do iterable.cast<int>().toList() or [for (var v in iterable) v as int], but List.from can be shorter. Always provide a type variable to List.from.
So, in general: Only use one of these constructors if you need a fixed-length list (passing growable: false), or if you want to down-cast the elements using List.from, and then always provide the type argument.
Otherwise use list literals. That's probably going to be more efficient too because it avoids some function calls.
List.generate - This is useful if the source of your list is either not of type List or if you need a special logic when you retrieve list elements;
List.of - Type checking is done at compile time.
List.from - Type checking is only done during runtime.
Both List.of and List.from work the same. But you should prefer List.of over List.from to ensure type checking is performed as early as compile time.
If you want to look more closely, take a look at this example: https://dartpad.dev/b9cd4acdeec266cb366155c6ec40b4f1

How to add values to a mutable list to then add to an immutable one

So I am using a custom SDK where I need to input a range of numbers, say from 1 to 100 as Strings into a listOf collection. Is there some efficient way this could be done with say a for loop? I barely have any experience with kotlin so all help is appreciated!
You can't really "add to an immutable [list]".
If you are already using a mutable list somewhere, then you can use toList() (like in #anber's answer) to get a read-only version or you could also directly pass it to a function expecting a List (if you don't change the list while the framework is using it).
If you simply want to build an immutable list of number strings from a range of numbers, this can be achieved using basic functional operations starting from the range object itself:
val list = (1..100).map { "$it" }
Note the Kotlin range syntax here. That way you don't really have to use a for loop, and you don't even have to use a temporary mutable list. Mutable stuff is not very idiomatic in Kotlin, unless it's part of the business.
You could also use it.toString() instead of the string template, but I find it more readable with the template.
If I understand you correctly you can create mutable list, add items in loop, and then convert it to immutable list:
val mutableList = mutableListOf<String>()
for (i in 0..10) {
mutableList.add(i.toString())
}
val immutableList = mutableList.toList()
There is a function which looks like a constructor, but is actually top-level function. You can use it like this:
val l = List(99) { "${it + 1}" }
l will be of type List<String> (immutable).

How to add element to existing list without creating new variable in erlang?

I have a list contains some elements and now with the help of lists:foreach I am fetching some more records and I want to append each value to my existing list elements without creating new variable as doing in other languages with help of array.
Here is my sample code which I am getting:
exception error: no match of right hand side value [6,7,1].
Sample Code:
listappend() ->
A = [1,2,3,4,5],
B = [6,7],
lists:foreach(fun (ListA) ->
B = lists:append(B, [ListA])
end, A),
B.
I want output like,
B = [6,7,1,2,3,4,5].
First of all, this feature already exists, so you won't need to implement it yourself. In fact, the list can take two lists as arguments:
1> lists:append([1,2,3,4,5], [6,7]).
[1,2,3,4,5,6,7]
Which is actually implemented as:
2> [1,2,3,4,5] ++ [6,7].
[1,2,3,4,5,6,7]
Please bear in mind that the ++ operator will copy the left operand, so this operation can easily lead to quadratic complexity. Said that, you probably want to construct your lists using the "cons" operator (eventually reversing the list at the end of the computation):
3> [1|[2,3,4,5,6,7]].
[1,2,3,4,5,6,7]
In any case, you can have two arguments in your function, which are the two lists to append, instead of defining them in the body of the function. This way, the values of A and B will change every time you call the my_append/2 function.
my_append(A, B) ->
YOUR_CODE_GOES_HERE
As a note and regarding the actual error you're getting, this is due to the following line:
B = lists:append(B, [ListA])
During each iteration, you're binding a new value to the variable B, which is already bound to the value [6,7].
Variables in Erlang are immutable. That means you cannot assign a new value to a variable once it has been bound, and this is why you get the 'no match' error. The old value does simply not match the new value you are trying to assign to the variable. Instead, you can create a new list using e.g lists:append based on the old one. You should probably start by looking at recursion and how you can use it to manipulate lists.

Non deprecated way of appending an element to a List in Scala 2.7.5?

How do you add an element to a List in Scala 2.7.5, without creating a new List and without using a deprecated solution.
You could use a ListBuffer, which provides constant time append:
val buffer = new scala.collection.mutable.ListBuffer[Int]
buffer += 1
buffer += 2
val list = buffer.toList
It's worth pointing out that List has a very specific meaning in scala, which is not equivalent to the java.util.List interface. List is a sealed, abstract class representing a recursive data-structure which has a head and a tail. (There do exist Java list-like structures in scala, some of which are mutable.)
Scala's Lists are immutable; modifying a list in any way is not possible, although you can create a new list be prepending to an existing one (which gives a new object back). Even though they are immutable, the structure is no more expensive in terms of object creation than, say, appending to a java.util.LinkedList
The + method has been deprecated for good reason because it is inefficient; instead use:
val newList = theList ::: List(toAppend)
I suppose a different way would be to prepend with 2 reversals:
val newList = (toAppend :: theList.reverse).reverse
I doubt this is any more efficient! In general, if I want append behaviour, I use prepend and then reverse (at the point of needing to access the list):
val newList = toAppend :: theList
//much later! I need to send the list somewhere...
target ! newList.reverse
Non deprecated way of appending an
element to a List in Scala 2.7.5?
That does not exist, and it will never exist.
How do you add an element to a List in
Scala 2.7.5, without creating a new
List and without using a deprecated
solution.
Use :::
val newList = element :: oldList
Or, if list is a var,
list ::= element
It does not create a new List (though, it creates a new ::, also known as cons), and it adds an element to it.
If you want to append elements to a sequence without creating a new sequence, use a mutable data structure.
The += method on a list is deprecated because it adds an element to the tail, which is expensive. The least expensive way of adding an element to a list is to add to the head using ::=.
So the deprecation warning is a subtle hint that you should redesign your program to work by prepending instead of appending:
scala> var l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l ::= 4
scala> l
res1: List[Int] = List(4, 1, 2, 3)
(Note that ::= and += on a var are not real methods, but sugar for l = l :: elem, etc)
This should do it:
http://www.scala-lang.org/docu/files/api/scala/collection/mutable/SingleLinkedList.html#append%28This%29
Or this:
http://www.scala-lang.org/docu/files/api/scala/collection/mutable/ListBuffer.html#%2B%3A%28A%29
The basic trick is to use a mutable List (or class with similiar functionality)
The following is not true for certain operations List implementation. Thanks to sschaef for the correction.
A very important point that I haven't seen mentioned here is that creating a new collection from another collection necessarily isn't as expensive in Scala as it is in Java. This concept is called persistence. Daniel Spiewak lays it out in his article, http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-1.
Here is a snippet of the relevant section,
Of course, the natural question which comes to mind is, what about performance? If each invocation actually creates a brand new Set for every recursive call, doesn’t that require a lot of inefficient object copying and heap operations? Well, as it turns out, this isn’t really the case. Yes, a new instance must be created at each turn, which is is a comparatively expensive operation on the JVM, but almost nothing is being copied. All of Scala’s immutable data structures have a property known as persistence, which means that you don’t copy the data out of the old container when creating a new, you just have the new reference the old and treat all of its contents as if they were its own.
So while it will be less expensive to use a mutable list it isn't as much of a concern as it is under Java.