why map on list generates extra [] - maple

Why does
map(x->print(x),[1,2,3]);
generate
1
2
3
[]
Where did the [] come from? According to help, .
The map commands apply fcn to the operands or elements of expr.
and
op([1,2,3]);
gives
1, 2, 3
But it seems here that fcn was also applied to the list itself, i.e. op(0,[1,2,3])

This is correct behaviour from map.
The print command returns NULL.
foo := print(1);
1
foo :=
lprint(foo);
NULL
The map command applied to a list will always return a list. The return value of map is not the return value of any of the calls to the first argument (operator) passed to map.
Let's make another example, with another procedure which returns NULL.
f := proc(x) NULL; end proc:
map(f, [1,2,3]);
[]
So every entry of the original list [1,2,3] gets replaced by NULL, which results in an expression sequence of three NULLs, which ends up being NULL. So the final result from applying map here is [NULL] which produces the empty list [].
bar := NULL, NULL, NULL;
bar :=
lprint(bar);
NULL
[ NULL, NULL, NULL ];
[]
If you don't want to see the empty list returned from map on your example then terminate the statement with a full colon.
If you do it using seq instead of map then the return value will be the just NULL (since it produces the expression-sequence of three NULLs, which as shown above becomes just NULL).
seq(print(x), x=[1,2,3]);
1
2
3
lprint(%);
NULL

Related

MATLAB's mxGetFieldByNumber and mxGetFieldNameByNumber return incongruent results

I have a C mex routine that is iterating over subfields of a structure. Sometimes calling mxGetFieldByNumber() returns NULL when mxGetFieldNameByNumber() returns a string for the same field idx. Here is a toy:
numFields = getNumberOfFields( currentField );
for( fieldIdx = 0; fieldIdx < numFields; fieldIdx ++){
subField = mxGetFieldByNumber( currentField, 0 , fieldIdx );
fieldName = mxGetFieldNameByNumber(currentField, fieldIdx );
}
I have read through the documentation of both functions. A NULL can be returned if (in this example) currentField were not a mxArray which I know is not the case because mxGetFieldNameByNumber() returns something sensible. Insufficient heap space could be the problem but I've checked that and it is on 400kb. NULL can also be returned when no value is assigned to the specified field but I've looked and it appears the value is zero.
Any thoughts?
When a struct is created at the MATLAB level or in a mex routine via mxCreateStruct, not all field elements are necessarily populated. In such case, MATLAB physically stores a NULL pointer (i.e., 0) in those data spots (a struct is essentially an array of mxArray pointers). E.g., take the following code snippet assuming X doesn't exist yet:
X.a = 5;
X(2).b = 7;
The X struct variable actually has four elements, namely X(1).a, X(1).b, X(2).a, and X(2).b. But you only set two of these elements. What does MATLAB do with the other elements? Answer: It simply stores NULL pointers for those spots. If you subsequently access those NULL spots in your MATLAB code, MATLAB will simply create an empty double matrix on the fly.
At the mex level, a similar thing happens. When you first create the struct with mxCreateStruct, MATLAB simply fills all of the element spots with NULL values. Then you can populate them in your code if you want, but note that leaving them as NULL is perfectly acceptable for returning back to MATLAB. The routine mxGetFieldByNumber actually gets the element mxArray pointer, and mxGetFieldNameByNumber gets the name of the field itself ... two very different things. If you get a NULL result from a valid mxGetFieldByNumber call (i.e. your index is not out of range), that simply means this element was never set to anything. You should never get a NULL result from a valid mxGetFieldNameByNumber call, since all field names are required to exist.
If you were to pass in the X created above to a mex routine and then examine prhs[0] you would find the following:
mxGetFieldByNumber(prhs[0],0,0)
returns a pointer to an mxArray that is the scalar double 5
mxGetFieldByNumber(prhs[0],0,1)
returns a NULL pointer
mxGetFieldByNumber(prhs[0],1,0)
returns a NULL pointer
mxGetFieldByNumber(prhs[0],1,1)
returns a pointer to an mxArray that is the scalar double 7
mxGetFieldNameByNumber(prhs[0],0)
returns a pointer to the string "a"
mxGetFieldNameByNumber(prhs[0],1)
returns a pointer to the string "b"

unique with "with" operator in systemverilog

I am a new SystemVerilog user and I have faced a strange (from my point of view) behavior of combination of unique method called for fixed array with with operator.
module test();
int arr[12] = '{1,2,1,2,3,4,5,8,9,10,10,8};
int q[$]
initial begin
q = arr.unique() with (item > 5 ? item : 0);
$display("the result is %p",q);
end
I've expected to get queue {8,9,10} but instead I have got {1,8,9,10}.
Why there is a one at the index 0 ?
You are trying to combine the operation of the find method with unique. Unfortunately, it does not work the way you expect. unique returns the element, not the expression in the with clause, which is 0 for elements 1,2,3,4 and 5. The simulator could have chosen any of those elements to represent the unique value for 0(and different simulators do pick different values)
You need to write them separately:
module test();
int arr[$] = '{1,2,1,2,3,4,5,8,9,10,10,8};
int q[$]
initial begin
arr = arr.find() with (item > 5);
q = arr.unique();
$display("the result is %p",q);
end
Update explaining the original results
The with clause generates a list of values to check for uniqueness
'{0,0,0,0,0,0,0,8,9,10,10,8};
^. ^ ^ ^
Assuming the simulator chooses the first occurrence of a replicated value to remain, then it returns {arr[0], arr[7], arr[8], arr[9]} from the original array, which is {1,8,9,10}

"operator symbol not allowed for generic subprogram" from Ada

I want to make subprogram for adding array's elements with Ada.
subprogram "Add_Data" have 3 parameters-
first parameter = generic type array (array of INTEGER or array of REAL)
second parameter = INTEGER (size of array)
third parameter = generic type sum (array of INTEGER -> sum will be INTEGER, array of REAL -> sum will be REAL)
I programmed it from ideone.com.
(I want to see just result by array of INTEGER. After that, I will test by array of REAL)
With Ada.Text_IO; Use Ada.Text_IO;
With Ada.Integer_Text_IO; Use Ada.Integer_Text_IO;
procedure test is
generic
type T is private;
type Tarr is array (INTEGER range <>) of T;
--function "+" (A,B : T) return T;
--function "+" (A, B : T) return T is
--begin
-- return (A+B);
--end "+";
procedure Add_Data(X : in Tarr; Y : in INTEGER; Z : in out T);
procedure Add_Data(X : in Tarr; Y : in INTEGER; Z : in out T) is
temp : T;
count : INTEGER;
begin
count := 1;
loop
temp :=temp+ X(count); //<-This is problem.
count := count + 1;
if count > Y then
exit;
end if;
end loop;
Z:=temp;
end Add_Data;
type intArray is array (INTEGER range <>) of INTEGER;
intArr : intArray := (1=>2, 2=>10, 3=>20, 4=>30, 5=>8);
sum : INTEGER;
procedure intAdd is new Add_Data(Tarr=>intArray, T=>INTEGER);
begin
sum := 0;
intAdd(intArr, 5, sum);
put (sum);
end test;
when I don't overload operator "+", It makes error.
"There is no applicable operator "+" for private type "T" defined."
What can I do for this?
If a generic’s formal type is private, then nothing in the generic can assume anything about the type except that it can be assigned (:=) and that it can be compared for equality (=) and inequality (/=). In particular, no other operators (e.g. +) are available in the generic unless you provide them.
The way to do that is
generic
type T is private;
with function "+" (L, R : T) return T is <>;
This tells the compiler that (a) there is a function "+" which takes two T’s and returns a T; and (b) if the actual T has an operator "+" which matches that profile, to allow it as the default.
So, you could say
procedure intAdd is new Add_Data (T => Integer, ...
or, if you didn’t feel like using the default,
procedure intAdd is new Add_Data (T => Integer, "+" => "+", ...
In addition to not knowing how to declare a generic formal subprogram (Wright has shown how to do this for functions), your code has a number of other issues that, if addressed, might help you move from someone who thinks in another language and translates it into Ada into someone who actually uses Ada. Presuming that you want to become such a person, I will point some of these out.
You declare your array types using Integer range <>. It's more common in Ada to use Positive range <>, because people usually refer to positions starting from 1: 1st, 2nd, 3rd, ...
Generics are used for code reuse, and in real life, such code is often used by people other than the original author. It is good practice not to make unstated assumptions about the values clients will pass to your operations. You assume that, for Y > 0, for all I in 1 .. Y => I in X'range and for Y < 1, 1 in X'range. While this is true for the values you use, it's unlikely to be true for all uses of the procedure. For example, when an array is used as a sequence, as it is here, the indices are immaterial, so it's more natural to write your array aggreate as (2, 10, 20, 30, 8). If I do that, Intarr'First = Integer'First and Intarr'Last = Integer'First + 4, both of which are negative. Attempting to index this with 1 will raise Constraint_Error.
Y is declared as Integer, which means that zero and negative values are acceptable. What does it mean to pass -12 to Y? Ada's subtypes help here; if you declare Y as Positive, trying to pass non-positive values to it will fail.
Z is declared mode in out, but the input value is not referenced. This would be better as mode out.
Y is not needed. Ada has real arrays; they carry their bounds around with them as X'First, X'Last, and X'Length. Trying to index an array outside its bounds is an error (no buffer overflow vulnerabilities are possible). The usual way to iterate over an array is with the 'range attribute:
for I in X'range loop
This ensures that I is always a valid index into X.
Temp is not initialized, so it will normally be initialized to "stack junk". You should expect to get different results for different calls with the same inputs.
Instead of
if count > Y then
exit;
end if;
it's more usual to write exit when Count > Y;
Since your procedure produces a single, scalar output, it would be more natural for it to be a function:
generic -- Sum
type T is private;
Zero : T;
type T_List is array (Positive range <>) of T;
with function "+" (Left : T; Right : T) return T is <>;
function Sum (X : T_List) return T;
function Sum (X : T_List) return T is
Result : T := Zero;
begin -- Sum
Add_All : for I in X'range loop
Result := Result + X (I);
end loop Add_All;
return Result;
end Sum;
HTH

Assign a value to a single SFrame element

I want to assign a value to a single element (i.e. single row and column) in an SFrame.
I am using the Python Notebook and importing graphlab.
I created an SFrame with dimensions 16364 rows x 37 columns.
The column 'test' contains zeros.
I have used the following syntax to set the value:
sf[1]['test'] = 3;
If I then type:
sf[1]['test']
then I see the correct value, i.e "3"
But if I type:
sf
then I just see values of zero for all rows of column 'test'
Also same for sf.head() or sf['test'] or sf['test'].head()
I don't understand why one syntax shows the value of "3" where an alternative one does not. Is the value in sf[1]['test'] 3 or 0 ?
SFrames are immutable, so they don't actually support item assignment. The reason for the difference you see here is because
sf[1]['test']
isn't actually referring to the SFrame at all. "sf[1]" returns a dictionary with keys that match to the SFrame's column names, and values that match the second row of the SFrame. When you assign a number to "sf[1]['test']", you are changing the value of the "test" key in the dictionary that was returned, so the SFrame "sf" is not involved in the assignment. The correct way to reference only the second value of the column "test" and assign the value "3" is this:
sf['test'][1] = 3
which would return this error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-c52dab41d5dd> in <module>()
----> 1 sf['test'][1] = 3
TypeError: 'SArray' object does not support item assignment

comparison(4) is only possible for atomic and list types

I have a 54x2 character matrix(totallist) which stores the locations of different input files. I've declared a function inside which I've a loop wherein row by row values are extracted from the 54x2 character matrix, stored in a data frame(named ACC) and then subsetting is done.
names(read.delim(totallist[1,1]))
[1] "stock" "firstsymbol" "date" "dhm" "nooftrades" "totqty" "openprice" "closeprice" "highprice"
[10] "lowprice" "wtdavgprice" "modeprice"
Below is the function declaration: I pass totallist as an argument
function (y)
{
for(i in 1:54)
{
ACC <- read.delim(y[i,1])
Acc.sub=subset(ACC,date<=20100331 & dhm%%10000<1531 & date!=20100206,select=c(dhm,closeprice))
}
}
I'm getting the following error message:
Error in date <= 20100331 :
comparison (4) is possible only for atomic and list types