What's the difference between [] and elementAt in List? - dart

var ints = [0, 1, 2, 3];
var foo = ints.elementAt(1);
var bar = ints[1];
assert(foo == bar);
Both elementAt and [] operator do the same job. Is there any difference between the two and if no, then why there is no [] defined in Iterable class when we can use elementAt on them?

then why there is no [] defined in Iterable class when we can use elementAt on them?
You've sort of answered your own question: the difference is that elementAt is defined for all Iterables, and operator [] isn't.
In most languages, [] is usually expected to be fast: it's often O(1) or O(log n). Allowing [] to access elements of a linked list would be technically possible, but it usually would be a bad idea since it'd make potential performance problems less obvious. Most people would not expect someCollection[99] to perform 100 iterations.
In contrast, elementAt does not make any such guarantee:
May iterate through the elements in iteration order, ignoring the first index elements and then returning the next. Some iterables may have a more efficient way to find the element.
So any Iterable always can provide an elementAt implementation, which is not necessarily fast, but only derived classes that can provide efficient implementations should provide operator []. For such classes, elementAt and [] should be the same.

Related

Parse a tuple of strings to usize

What is the idiomatic way of parsing ("5", "6") to (5, 6)? I have already tried calling .map(String::parse::<usize>) but that doesn't work because tuples are not iterators. Nor can I call .into_iter().
Tuples are meant to be heterogeneous collections and as such you can't really iterate over them, as different elements can, in principle, have different types.
So the easiest way is just
let a: usize = my_tuple.0.parse()?;
let b: usize = my_tuple.1.parse()?;
and if you need something more "sophisticated" you'll have to use a macro:
How to iterate or map over tuples?
This might seem unnecessarily cumbersome when you compare it with Python, where tuples are indeed iterable. But that's because you have dynamic and duck typing in Python, so the fact that tuples can be heterogeneous (different datatypes in different positions) isn't that big of a deal.
Think about it. What would even the signature be for the closure to pass to map in a tuple of type, say, (i32, String, Option<f64>)?

DART - Why 'set' data structure is told to be unordered?

I see in dart tutorial's websites that ((A set is an unordered collection of values. We can’t get the values by their index values as they are unordered.)) but we can:
main(List<String> args) {
Set a = Set();
a.add(10);
a.add(20);
a.add(40);
a.add(50);
var p = a.elementAt(0);
print(p);
}
so what is the meaning of the unordered collection??
I see Andreas Florath's Answer too :
Why 'set' data structure is told to be unordered?
but I didn't understand.
can anyone help to understand what's the meaning of unordered?
Depending on the type of Set, it might be one that optimizes for preserving order, or it might be one that optimizes for look-up speed, or it might be one that optimizes for insertion speed. You can't get all three at once. Take a look at each of the "implementors" in the Set documentation (https://api.flutter.dev/flutter/dart-core/Set-class.html), which also says:
A HashSet is unordered, which means that its iteration order is
unspecified, LinkedHashSet iterates in the insertion order of its
elements, and a sorted set like SplayTreeSet iterates the elements in
sorted order.

Why implement an immutable list as a linked-list?

According to F#'s list documentation:
"A list in F# is an ordered, immutable series of elements of the same type"
"Lists in F# are implemented as singly linked lists"
Why not implement it contiguously in memory since it immutable and thus has a fixed size? Why ever use an F# list instead of an F# array?
They serve different purposes, for instance:
You use an Array in F# to store big amounts of data that needs to be accessed randomly with relative low overhead.
A List in F# is useful when you need to accumulate something over iterations of a recursive function. Arrays don't play well here, since they have a fixed size.
With a list, you can prepend all elements of ListM (size M) to ListN (size N) in O(M) time. Similarly, you can prepend a single Element to any list in O(1) time.

Increasing the length of a tuple in Erlang

How can I increase the length of a tuple in Erlang? For example, suppose Tup={1,2,3}, and now I want to add another element to it. Is there any way to do this?
Tuple is not suppose to be a flexible data structure. If you are resizing it often, then you should consider using other erlang data structures like lists, maps or sets - depends on your expectation. Here is nice introduction to key-value stores.
But if you really have to extend that tuple, then you can use erlang:append_element/2:
{1,2,3,4} = erlang:append_element({1,2,3}, 4).
Tuples aren't mutable so you can't, strictly speaking, increase the length.
Generally, if you want a variable-number-of-things datatype, a tuple will be very inconvenient. For example, iterating over all elements of a list is highly idiomatic, while iterating over all elements of a tuple whose size is unknown at compile-time is a pain.
However, a common pattern is to get a tuple as a result from some function and return elements of that tuple plus additions.
country_coords(Name) ->
{Lat, Lng} = find_address(Name),
{_Street, _City, _Zip, Country} = geocode(Lat, Lng),
{ok, Lat, Lng, Country}.
erlang:append_element(tuple_whose_length_to_increase, element_to_be).This is the inbuilt function but tuples,lists are not meant to be flexible.So avoid using this function unless there is no other way

Am I missing something, or do we have a couple inconsistencies / misnomers?

Mathematicians typically count starting with 1, and call the counting variable n (i.e. "the nth term of the sequence). Computer scientists typically count starting with 0, and call the counting variable i (i.e. "the ith index of the array"). Which is why I was confused to learn that Seq.nth actually returns the "n+1 term of the sequence".
Doubly confusing is that Seq.iteri does as it's name implies and traverses a sequence supplying the current index.
Am I missing something? Is there a rational / history for this misnomer / inconsistency? Or was it just a mistake (which likely can't be fixed since we have a commercial release now).
Edit
Admittedly my claim about conventional use of i and n is not strictly true and I should have been more careful about such an assertion. But I think it is hard to deny that the most popularly used languages do start counting at 0 and that i and j are most certainly extremely popular choices for index variable names. So, when I am familiar with using Seq.iteri and Seq.mapi and then come across Seq.nth I think it is reasonable to think, "Oh, this function counts differently, probably the other way things are counted, starting with 1."
And, as I pointed out in the comments, the summaries for Seq.iteri, Seq.mapi, and Seq.nth only served to enforce my assumption (note that intellisense only gives you the summaries, it does not give you the description of each parameter which you have to find on MSDN):
Seq.iter
Applies the given function to each
element of the collection. The integer
passed to the function indicates the
index of element.
Seq.mapi
Creates a new collection whose
elements are the results of applying
the given function to each of the
elements of the collection. The
integer index passed to the function
indicates the index (from 0) of
element being transformed.
Seq.nth
Computes the nth element in the
collection.
Note the emphasis on "nth", not mine, as if everyone knows what the nth element in the sequences is as opposed to the ith element.
Talking of history, nth is zero based in Lisp, which is probably what the F# function is named for. See the common lisp spec for nth.
I haven't found your statement about i and n in mathematics to be true; usually n is the number of something rather than an index. In this case, it was the number of times to call cdr to get the next element.
Arrays are indexed starting from 0 in many computer languages, but some languages start from 1 and some allow a choice. Some allow the index range to be set as part of the array declaration, or even to be changed at runtime.
Mathematicians are as likely to start at zero as one, sometimes use other index ranges, and attach no particular meaning to the letters 'n' and 'i'.
The method names Seq.nth and Seq.iteri are poorly named.

Resources