I am learning Dart, and I defined a sum function to sum list of numbers.
sum(numberList) => numberList.reduce((num a, num b) => a + b);
When I call it on list of numbers:
main() {
var nl = [4, 2, 4, 5, 9];
print(sum(nl));
}
I got error:
type '(num, num) => num' is not a subtype of type '(int, int) => int' of 'combine'
This confused me, why a function defined for type num cannot be called on list of int? How to fix this problem? If the list 'nl' is coming from outside of my code, how can I cast list of int to list of num? (It seems List of int is not a list of num? puzzled.)
The problem is that you are calling reduce on a List<int>.
The type of that is int reduce(int Function(int, int) combine).
That means that the combine function argument must be a function returning an int.
You try to pass a function which returns a num, and that is not allowed.
You didn't catch that statically because you haven't typed the argument to sum.
Try changing it to:
num sum(List<num> numberList) => numberList.reduce((num a, num b) => a + b);
What you can do is cast the list to List<num> before passing it to sum:
print(sum(nl.cast<num>()));
I'm sorry I cannot give a real answer to your but here are some methods so solve your issue.
First of all obviously cast your list to an num list, either by specifying the generic type or using .cast :
var nl = [4, 2, 4, 5, 9];
print(sum(nl.cast<num>()));
var nl = <num>[4, 2, 4, 5, 9];
print(sum(nl2));
or you might want to use an extension which will work just fine for any list type which extends num:
extension SumList<T extends num> on List<T> {
T sum() => reduce((a, b) => a + b);
}
var nl4 = [4, 2, 4, 5, 9];
print(nl4.sum());
Related
I am not pro in Fortran95, but I am writing a code in it and I found that I want to mask the array values with -9999, if it does not have certain values.
Example: I have an array 'X' has values vary from 0 to 32768, and I want to mask the values of the array, if 'X' value is not equal to 0,1,2,16 or 18. I solved it with the following syntax:
if (X.eq.0.or.X.eq.1.or.X.eq.2.or.X.eq.16.or.X.eq.18) then
X=X
else
X=-9999
end if
But there any other way to mask array values in FORTRAN 95?
There is the where statement that can mask the array, but given the logical you have shown its a bit ugly
where (.not.(X==0 || X==1 || X==2 || X==16 || X==18)) x = -9999
For these kinds of problems I find it convenient to define the .in. operator, which returns whether or not a scalar is in an array, so:
1 .in. [0, 1, 2] returns .true.
3 .in. [0, 1, 2] returns .false.
[1, 3] .in. [0, 1, 2] returns [.true., .false.]
This can be defined as
module in_module
implicit none
interface operator(.in.)
module procedure element_in_list
module procedure elements_in_list
end interface
contains
function element_in_list(lhs, rhs) result(output)
integer, intent(in) :: lhs
integer, intent(in) :: rhs(:)
logical :: output
output = any(lhs==rhs)
end function
function elements_in_list(lhs, rhs) result(output)
integer, intent(in) :: lhs(:)
integer, intent(in) :: rhs(:)
logical, allocatable :: output(:)
integer :: i
output = [(any(lhs(i)==rhs), i=1, size(lhs))]
end function
end module
With the .in. operator defined, then if X is an array you can write
where (.not. (X .in. [0, 1, 2, 16, 18])) X = -9999
which will convert e.g. X = [4, 5, 1, 3, 16] to X = [-9999, -9999, 1, -9999, 16].
If you want to simplify things further (as the where construct can be quite unwieldy), you can also define the function filter which takes an array of logicals and returns the indices of the .true. values, e.g. filter([.false., .true., .true.]) returns [2, 3].
This can be defined as:
function filter(input) result(output)
logical, intent(in) :: input(:)
integer, allocatable :: output(:)
integer :: i
output = pack([(i, i=1, size(input))], input)
end function
And then you can simply write
X(filter(.not. (X .in. [0, 1, 2, 16, 18]))) = -9999
I want to do the equivalent of this Python code in Dart. Possibly as a one liner I could use in a return statement.
m = {1: 'a', 2: 'b', 3: 'c'}
l = [1, 3]
[m[index] for index in l]
this results in a new list like this ['a', 'c']
A long version of this in Dart would be this.
List<String> r = [];
for (var key in l) {
r.add(m[key]);
}
I think this is what you are asking for:
void main() {
final m = {1: 'a', 2: 'b', 3: 'c'};
final l = [1, 3, 4];
List<String> r1 = m.entries.where((e) => l.contains(e.key)).map((e) => e.value).toList();
List<String> r2 = l.where((k) => m.containsKey(k)).map((k) => m[k]).toList();
print(r1); // [a, c]
print(r2); // [a, c]
}
Update 1: Added another example (r2) which iterate over the list instead.
Update 2: Added check to second solution so it only map keys there are in the map.
I'm relatively new to the Lua language and there's something I'm obviously missing about table structures.
I'm trying to create a table of tables, with each table in the table having a key and the value being the respective table.
Ok, that statement can be confusing. Here's an example:
{{ key = "RC", value = {1, 2, 3, 4}},
{ key = "M", value = {4, 8, 7}},
{ key = "D", value = {3, 8, 9}}
...}
for this I used the following algorithm:
local listOfLists = {};
...
if condition1 then
listOfLists[key1] = list1;
end
...
if condition2 then
listOfLists[key2] = list2;
end
...
And so on...
I hope to use the keys to later determine which lists have been added to the table.
But the thing is, no lists seem to be added to the table even if all the conditions are met.
I can use table.insert(listOfLists, list1) in place of listOfLists[key1] = list1 but then I won't be able to tell which lists were added to the collection.
Ant suggestions?
Lua tables are a flexible data structure. Elements are key-value pairs. A key is any Lua value except nil. A value can have any value except nil. Assigning nil to the value obliterates the pair.
The (possibly empty) subset of a table that has key values of the number type that are integers from 1 to n is called a sequence. n is determined as the last such key that is paired with a nil value. Several table functions and operators work only with sequences.
Table constructors allow several syntaxes for keys:
Implied via a sequence: {1, 2, 3}
Explicit keys: {[1] = 1, [3] = 3, ["two"] = "value"}
Identifier keys: {one = 1, two = 2}
A table constructor can use any combination of them.
You have defined a sequence of elements, each of which is a table with two elements, the
second of which is a sequence.
It appears you want keys to be strings and values to be sequences:
{
RC = {1, 2, 3, 4},
M = {4, 8, 7},
D = {3, 8, 9}
}
It's hard to understand, what do you wanna achieve. So, if you want more specific answer, provide more info.
You can create associative table of tables.
local map = {}
map["key"] = { 1, 2, 3, 4 }
print(map.key[3])
Or you can create an array of tables
local vector = {}
vector[1] = { 1, 2, 3, 4 }
print(vector[1][2])
Or you can combine approaches.
To create
{{ key = "RC", value = {1, 2, 3, 4}},
{ key = "M", value = {4, 8, 7}},
{ key = "D", value = {3, 8, 9}}
...}
You can use table constructor or smth from code.
local tbl = { { key = "RC", value = {1, 2, 3, 4}} } -- init first elem from constructor
table.insert(tbl, { key = "M", value = {4, 8, 7}}) -- table insert & constructor
tbl[2] = {} -- Array-based access.
tbl[2].key = "D" --key access
tbl[2]["value"] = { 3, 8, 9 } -- other way
Note, that each table consists of two parts: vector for sequental keys from 1 to N, and map otherwise. Some functions, like table length operator or ipairs iterator are guaranteed to work only with vector-part of table. But they are significantly faster.
EDIT: (last paragraph explanation)
If you have a table with some keys and want to iterate through, you can use ipairs or pairs.
ipairs is ordered, and goes from 1 to first not-nil element. It doesn't iterate over not-integer keys. pairs goes trough any key, but doesn't guarantee order.
local map = { 1, 2, 3, key = 6, [5] = 5 }
for i, v in ipairs(map) do
print(v) -- will output 1, 2, 3. first nil element is map[4]. map[5] will mot be visited.
end
for i, v in pairs(map) do -- NOTE pairs usage
print(v) -- will output 1, 2, 3, 5, 6 in ANY order
end
map[4] = 4 -- Fill gap
for i, v in ipairs(map) do
print(v) -- will output 1, 2, 3, 4, 5. Now first nil element is map[6]
end
Length operator works similar to ipairs, it doesn't count elements not visited by ipairs method.
table.maxn works with numerical indices, and will return zero for your table.
Reference say that table.maxn
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)
Little example about length and table.maxn
local a = { 1, 2, 3, [5] = 5}
print(table.maxn(a)) -- 5
print(#a) -- 3
a = { key = 4 }
print(table.maxn(a)) -- 0
print(#a) -- 0
print(a["key"]) -- 4, nothing is lost
local num = 0
for _, __ in pairs(a) do num = num + 1 end
print(num) -- 1 We find it.
Example. I've got an array with 15 objects. I want to start enumerating from a given index. Say start at index 5 and then the index above, the index under, above, under etc... I do want it to wrap around.
So the order of indexes in my example would be. 5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0, 11, 14, 12, 13
It would be great to have a method signature similar to following line, but I don't require that to approva an answer:
- (void)enumerateFromIndex:(NSUInteger)index wrapAroundAndGoBothWays:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
How can this be done? Would like to avoid copying array etc.
At this post we do it with no wrap around: Enumerate NSArray starting at givven index searching both ways (no wrap around)
Borrowing from #omz, here is the wrapping variant, which is even simpler:
#implementation NSArray (Extensions)
- (void)enumerateFromIndex:(NSUInteger)index wrapAroundAndGoBothWays:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
{
BOOL stop = NO;
NSUInteger actual = index;
for (NSUInteger i = 0; i < self.count && !stop; i++) {
actual += (2*(i%2)-1)*i;
actual = (self.count + actual)%self.count;
block([self objectAtIndex:actual], actual, &stop);
}
}
#end
This is a mathematical problem. There is a nice solution. However, it involves sorting the list of indexes in advance.
The idea is to lay the integers from 0 to 15 out on a circle and taking the elements in the order they appear on an axis.
Since doing this in ObjC is so tedious, I present the python solution:
from math import pi, cos
def circlesort(N, start):
eps = 1e-8
res = range(N)
def f(x):
return -cos(2*pi*(x-start-eps)/N)
res.sort( lambda x,y:cmp(f(x), f(y)) )
return res
then
print circlesort(15, 5)
outputs
[5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0, 11, 14, 12, 13]
which is the desired result.
EDIT
Okay, here is a C implementation:
#include <stdlib.h>
#include <math.h>
#define sign(x) ((x)>0?1:(x)<0?-1:0)
void circlesort(int* values, int N, int start){
double f(int x)
{
return -cos(2*M_PI*((double)(x-start)-.25)/N);
}
int compare (const void * a, const void * b)
{
return sign( f(*(int*)a) - f(*(int*)b) );
}
qsort (values, N, sizeof(int), compare);
}
This will circlesort an array of integers of lenght N. Use it like this:
int i, N = 15;
int indexes[N];
for (i=0;i<N;i++)
indexes[i] = i;
circlesort(indexes, N, 5);
Now the array indexes is sorted in the desired order. Because there are nested functions, you should add -fnested-functions to the compiler flags.
EDIT 2
Considering the fact that there is a much simpler solution (see my other answer) this one is rather academic.
I hope that someone can shed a light on the (to me) unexpected behavioral difference between the two (result wise) equal queries.
A small program can be worth a thousand words, so here goes :
static void Main(string[] args)
{
var l1 = new List<int> { 1, 2, 3 };
var l2 = new List<int> { 2, 3, 4 };
var q1 = // or var q1 = l1.Join(l2, i => i, j => j, (i, j) => i);
from i in l1
join j in l2
on i equals j
select i;
var q2 = //or var q2 = l1.SelectMany(i => l2.Where(j => i == j));
from i in l1
from j in l2
where i == j
select i;
var a1 = q1.ToList(); // 2 and 3, as expected
var a2 = q2.ToList(); // 2 and 3, as expected
l2.Remove(2);
var b1 = q1.ToList(); // only 3, as expected
var b2 = q2.ToList(); // only 3, as expected
// now here goes, lets replace l2 alltogether.
// Afterwards, I expected the same result as q1 delivered...
l2 = new List<int> { 2, 3, 4 };
var c1 = q1.ToList(); // only 3 ? Still using the previous reference to l2 ?
var c2 = q2.ToList(); // 2 and 3, as expected
}
Now I know that Join internally uses a lookup class to optimize performance, and without too much knowledge, my guess is that the combination of that with captured variables might cause this behavior, but to say I really understand it, no :-)
Is this an example of what Joel calls "a leaky abstraction" ?
Cheers,
Bart
You're actually nearly there, given your query expansions in the comments:
var q1 = l1.Join(l2, i => i, j => j, (i, j) => i);
var q2 = l1.SelectMany(i => l2.Where(j => i == j));
Look at where l2 is used in each case. In the Join case, the value of l2 is passed into the method immediately. (Remember that the value is a reference to the list though... changing the contents of the list isn't the same as changing the value of l2.) Changing the value of l2 later doesn't affect what the query returned by the Join method remembers.
Now look at SelectManay: l2 is only used in the lambda expression... so it's a captured variable. That means that whenever the lambda expression is evaluated, the value of l2 at that moment in time is used... so it will reflect any changes to the value.