Dart, what is the "where" keyword - flutter

I've seen the occasional list.where() code on stackoverflow.
So I'm trying to figure this out.
How is it different from .map()?
Where can I read the documentation to learn in detail about this?
(firstWhere, startWith ... etc very complex queries with => keywords)

Here are the methods workings in example:
final list = [1, 2, 3, 4];
// List.where is used to filter out element based on a condition
list.where((element) => element.isOdd); // [1, 3]
// List.map allows you to map each value to a new one (not necessarily of the same type)
list.map((element) => 2*element); // [2, 4, 6, 8]
Where to read this information
One of the best thing of dart (and flutter) is its source code documentation. In most code editors, you can ctrl+click on a method to see the documentation. From there you can learn what it does and there are sometimes example.
Another great place is StackOverflow of course, since those question are asked over and over, especially basic ones like this which are often the same across different languages.

you can read it from here
the difference between where and map is basically this, where return a new list "iterable" with only the elements that satisfies the passed test, and map return also a new list (but with the same length), each element is mapped with the passed function to different value (wether the same type or a completely different type)

Related

why is the map function inherently parallel?

I was reading the following presentation:
http://www.idt.mdh.se/kurser/DVA201/slides/parallel-4up.pdf
and the author claims that the map function is built very well for parallelism (specifically he supports his claim on page 3 or slides 9 and 10).
If one were given the problem of increasing each value of a list by +1, I can see how looping through the list imperatively would require a index value to change and hence cause potential race condition problems. But I'm curious how the map function better allows a programmer to successfully code in parallel.
Is it due to the way map is recursively defined? So each function call can be thrown to a different thread?
I hoping someone can provide some specifics, thanks!
The map function applies the same pure function to n elements in a collection and aggregates the results. It doesn't matter the order in which you apply the function to the members of the collection because by definition the return value of the function is purely dependent upon the input.
The others already explained that the standard map implementation isn't parallel.
But in Scala, since you tagged it, you can get the parallel version as simply as
val list = ... // some list
list.par.map(x => ...) // instead of list.map(x => ...)
See also Parallel Collections Overview and documentation for ParIterable and other types in the scala.collection.parallel package.
You can find the implementation of the parallel map in https://github.com/scala/scala/blob/v2.12.1/src/library/scala/collection/parallel/ParIterableLike.scala, if you want (look for def map and class Map). It requires very non-trivial infrastructure and certainly isn't just taking the recursive definition of sequential map and parallelizing it.
If one had defined map via a loop how would that break down?
The slides give F# parallel arrays as the example at the end and at https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/array.fs#L266 you can see the non-parallel implementation there is a loop:
let inline map (mapping: 'T -> 'U) (array:'T[]) =
checkNonNull "array" array
let res : 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length
for i = 0 to res.Length-1 do
res.[i] <- mapping array.[i]
res

Tuple structure equivalent in Matlab

In Haskell, there is a structure called 'tuples' which allows two elements to be paired together (Ie: (1,2), ('A', 'B') etc)
I was wondering if there was something similar in Matlab so that I could match elements and then query matlab in a way similar to "If element X is matched to Y then.. else.."
Thanks!
The closet thing I know of in MATLAB is to use a map object. They are pretty easy to use. You can create one as follows
someMap = containers.Map();
Adding a new key is pretty easy as well
someMap('someKey') = 'someValue';
The key needs to be a string by default, but this can be edited. You can also check if the key exists already by calling
someMap.isKey('someKey')
And values are accessed by just calling
someMap('someKey')
This should mimic the behavior that you are looking for. You can always read more by looking at the documentation. containers.Map
A simple cell array may be able to do the trick for you:
C = {1, 2; 'A' 'B'}
You can now easily perform tests on it, for example:
strcmp(C, 'A')

How to check if the value is a number in Prolog manually?

How to check if the given value is a number in Prolog without using built-in predicates like number?
Let's say I have a list [a, 1, 2, 3]. I need a way to check if every element within this list is a number. The only part of the problem that bothers me is how to do the check itself without using the number predicate.
The reason why I'm trying to figure this out is that I've got a college assignment where it's specifically said not to use any of the built-in predicates.
You need some built-in predicate to solve this problem - unless you enumerate all numbers explicitly (which is not practical since there are infinitely many of them).
1
The most straight-forward would be:
maplist(number, L).
Or, recursively
allnumbers([]).
allnumbers([N|Ns]) :-
number(N),
allnumbers(Ns).
2
In a comment you say that "the value is given as an atom". That could mean that you get either [a, '1', '2'] or '[a, 1, 2]`. I assume the first. Here again, you need a built-in predicate to analyze the name. Relying on ISO-Prolog's errors we write:
numberatom(Atom) :-
atom_chars(Atom, Chs),
catch(number_chars(_, Chs), error(syntax_error(_),_), false).
Use numberatom/1 in place of number/1, So write a recurse rule or use maplist/2
3
You might want to write a grammar instead of the catch... goal. There have been many such definitions recently, you may look at this question.
4
If the entire "value" is given as an atom, you will need again atom_chars/2or you might want some implementation specific solution like atom_to_term/3 and then apply one of the solutions above.

How do I handle dynamically-sized lists of controls in Play 2.0?

I really like Play 2.0's form mapping system, but I had a question about how to implement forms with lists of similar controls.
In Rails, if I had a list of form parameters like
foo[]=3, bar[]=4, foo[]=2, bar[]=5
I'd get a structure that looks like
[{:foo => 3, :bar => 4}, {:foo => 2, :bar => 5}].
In Play, I can do this by specifying explicit indices, e.g.
foo[0]=3, foo[1]=4, etc.
But for forms where I can dynamically add and remove list entries on the page before submitting the form to the server, this requires a little bookkeeping to make sure the indices are right. Does Play support something like Rails's approach, where I can add new foo/bar pairs to my forms and have each occurrence appear as a separate entry in an array?
The problem you have comes from the RepeatedMapping where the indexes function in the companion is simply collecting the ints, sorting them and finally distinct...
What could be done is to update the map to have indexes continuous...
So the only way, I can see so far at least, is to create the same kind of RepeatedMapping that will handle it... But I guess it could be added as a improvement of the functionality?

How to delete elements from a transformed collection using a predicate?

If I have an ArrayList<Double> dblList and a Predicate<Double> IS_EVEN I am able to remove all even elements from dblList using:
Collections2.filter(dblList, IS_EVEN).clear()
if dblList however is a result of a transformation like
dblList = Lists.transform(intList, TO_DOUBLE)
this does not work any more as the transformed list is immutable :-)
Any solution?
Lists.transform() accepts a List and helpfully returns a result that is RandomAccess list. Iterables.transform() only accepts an Iterable, and the result is not RandomAccess. Finally, Iterables.removeIf (and as far as I see, this is the only one in Iterables) has an optimization in case that the given argument is RandomAccess, the point of which is to make the algorithm linear instead of quadratic, e.g. think what would happen if you had a big ArrayList (and not an ArrayDeque - that should be more popular) and kept removing elements from its start till its empty.
But the optimization depends not on iterator remove(), but on List.set(), which is cannot be possibly supported in a transformed list. If this were to be fixed, we would need another marker interface, to denote that "the optional set() actually works".
So the options you have are:
Call Iterables.removeIf() version, and run a quadratic algorithm (it won't matter if your list is small or you remove few elements)
Copy the List into another List that supports all optional operations, then call Iterables.removeIf().
The following approach should work, though I haven't tried it yet.
Collection<Double> dblCollection =
Collections.checkedCollection(dblList, Double.class);
Collections2.filter(dblCollection, IS_EVEN).clear();
The checkCollection() method generates a view of the list that doesn't implement List. [It would be cleaner, but more verbose, to create a ForwardingCollection instead.] Then Collections2.filter() won't call the unsupported set() method.
The library code could be made more robust. Iterables.removeIf() could generate a composed Predicate, as Michael D suggested, when passed a transformed list. However, we previously decided not to complicate the code by adding special-case logic of that sort.
Maybe:
Collection<Double> odds = Collections2.filter(dblList, Predicates.not(IS_EVEN));
or
dblList = Lists.newArrayList(Lists.transform(intList, TO_DOUBLE));
Collections2.filter(dblList, IS_EVEN).clear();
As long as you have no need for the intermediate collection, then you can just use Predicates.compose() to create a predicate that first transforms the item, then evaluates a predicate on the transformed item.
For example, suppose I have a List<Double> from which I want to remove all items where the Integer part is even. I already have a Function<Double,Integer> that gives me the Integer part, and a Predicate<Integer> that tells me if it is even.
I can use these to get a new predicate, INTEGER_PART_IS_EVEN
Predicate<Double> INTEGER_PART_IS_EVEN = Predicates.compose(IS_EVEN, DOUBLE_TO_INTEGER);
Collections2.filter(dblList, INTEGER_PART_IS_EVEN).clear();
After some tries, I think I've found it :)
final ArrayList<Integer> ints = Lists.newArrayList(1, 2, 3, 4, 5);
Iterables.removeIf(Iterables.transform(ints, intoDouble()), even());
System.out.println(ints);
[1,3,5]
I don't have a solution, instead I found some kind of a problem with Iterables.removeIf() in combination with Lists.TransformingRandomAccessList.
The transformed list implements RandomAccess, thus Iterables.removeIf() delegates to Iterables.removeIfFromRandomAccessList() which depends on an unsupported List.set() operation.
Calling Iterators.removeIf() however would be successful, as the remove() operation IS supported by Lists.TransformingRandomAccessList.
see: Iterables: 147
Conclusion: instanceof RandomAccess does not guarantee List.set().
Addition:
In special situations calling removeIfFromRandomAccessList() even works:
if and only if the elements to erase form a compact group at the tail of the List or all elements are covered by the Predicate.