Netlogo - expected constant error - foreach

I have this line of code:
set SSB sum [foreach [foglie with [ipotetico? = false]] [((([media] of self ) - media-tot ) ^ 2) * ([larg] of self * [altez] of self)]]
foglie are an agentlist;
media-tot is a global variable
I cannot figure out why it gives me the error:
expected constant
I found the following loophole but it looks to me not elegant and maybe even slower:
set SSB 0
ask foglie with [ipotetico? = false] [ set SSB (SSB + (( [media] of self - media-tot) ^ 2) * ([larg] of self * [altez] of self)) ]
What do you think?
How can i make the first code to work?
Is the second code equivalent?

A good question will include a minimal example of the problem. In this case, in your first attempt above, it looks like you do not understand the difference between agentsets and lists, nor the use of foreach. So you need to read about this.
sum requires a list as input
to make a list with the bracket notation, you need to include only constants; otherwise, use list
putting an agentset in brackets does not produce a list, for the above reason, but even if you used list you would get a list containing the agentset as an element, not a list of the agents
foreach does not return a list (but map does)
Assuming media, larg, and altez are foglie attributes and media-tot is a global, you could have done the following:
sum [(media - media-tot) ^ 2 * (larg * altez)] of (foglie with [ipotetico? = false])

Related

List still being treated as a set even after converting

So i have an instance where even after converting my sets to lists, they aren't recognized as lists.
So the idea is to delete extra columns from a data frame comparing with columns in another. I have two data frames say df_test and df_train . I need to remove columns in df_test which are not in train .
extracols = set(df_test.columns) - set(df_train.columns) #Gives cols 2b
deltd
l = [extracols] # or list(extracols)
Xdp.dropna( subset = l, how ='any' , axis = 0)
I get an error : Unhashable type set
Even on printing l it prints like a set with {} curlies.
[{set}] doesn't cast to list, it just creates a list of length 1 with your set inside it.
Are you sure that list({set}) isn't working for you? Maybe you should post more of your code as it is hard to see where this is going wrong for you.

erlang : placeholder in tuple (or list)

I'd like to tidy my Eralng code, I found there're lots of issue following:
A = {Tid, _Tv0, _Tv1, Tv2, Tv3}
Is there any way to clean the code like to be: A = {Tid, SomewayReplace(4)} ???
Update1:
like #Pascal example, Is there any way to simple the code A = {T, _, _, _, _, _} like to be A = {T, SomewayReplace(4)} to replace that 4 symbol _ ???
update2
in real project, if some record include many element, I found it force me to repeat writing the symbol _, so I wonder if there is any way to simple it???
Writting A = Something means that you try to match A with Something or if A is unbound, assign Something to A. In anycase, Something must be defined.
You can find some shortcut in writting. For example, if you want to assign the result of a funtion to A, verify that the result is a tuple of 5 elements and assign the first element to T, the you can write:
A = {T,_,_,_,_} = f(Param).
The meaning of _T is exactly the same as any variable. It just says to th compiler to not issue a warning if this variable is not used in the code. It is frequent in pattern matching when you want to ignore the value of a variable but still keep trace of its meaning.
[edit]
It is not possible to write {T, SomewayReplace(4)}, but you may use records. A record is a tagged tuple (first element is the atom that identify this record. It is not shorter than placeholder for small tuples, but it is clearer, you don't need to remember the location of the information in your tuple, and it is easier to modify your code when you need to add a new element in a tuple. The syntax will be
-record(mytuple,{field1,...,fieldx,...}.
...
A = #mytuple{fieldx = T} = f(Param).
waerning: Records are managed by the compiler, so everything must be known at build time (#mytuple{Fieldx = T} is illegal, Fieldx cannot be a variable).
Why not use a record? Then you only match the fields you want to extract. As a by-effect, you make the code easier to debug, since you are forced to name the tuple by having a atom first.

How can Scala understand function calls in different formats?

I realize the following function calls are all same, but I do not understand why.
val list = List(List(1), List(2, 3), List(4, 5, 6))
list.map(_.length) // res0 = List(1,2,3) result of 1st call
list map(_.length) // res1 = List(1,2,3) result of 2nd call
list map (_.length) // res2 = List(1,2,3) result of 3rd call
I can understand 1st call, which is just a regular function call because map is a member function of class List
But I can not understand 2nd and 3rd call. For example, in the 3rd call, how can Scala compiler know "(_.length)" is parameter of "map"? How can compiler know "map" is a member function of "list"?
The only difference between variant 2 and 3 is the blank in front of the parenthesis? This can only be a delimiter - list a and lista is of course different, but a opening parens is a new token, and you can put a blank or two or three in front - or none. I don't see how you can expect a difference here.
In Java, there is no difference between
System.out.println ("foo");
// and
System.out.println("foo");
too.
This is the operator notation. The reason it works is the same reason why 2 + 2 works.
The space is used to distinguish between words -- listmap(_.length) would make the compiler look for listmap. But if you write list++list, it will work too, as will list ++ list.
So, one you are using operator notation, the space is necessary to separate words, but otherwise may be present or not.

matlab indexing into nameless matrix [duplicate]

For example, if I want to read the middle value from magic(5), I can do so like this:
M = magic(5);
value = M(3,3);
to get value == 13. I'd like to be able to do something like one of these:
value = magic(5)(3,3);
value = (magic(5))(3,3);
to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket on the first parenthesis before the 3.
Is it possible to read values from an array/matrix without first assigning it to a variable?
It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:
value = magic(5)(3, 3);
You can do this:
value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));
Ugly, but possible. ;)
In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:
subindex = #(A, r, c) A(r, c); % An anonymous function for 2-D indexing
value = subindex(magic(5), 3, 3); % Use the function to index the matrix
However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.
There was just good blog post on Loren on the Art of Matlab a couple days ago with a couple gems that might help. In particular, using helper functions like:
paren = #(x, varargin) x(varargin{:});
curly = #(x, varargin) x{varargin{:}};
where paren() can be used like
paren(magic(5), 3, 3);
would return
ans = 16
I would also surmise that this will be faster than gnovice's answer, but I haven't checked (Use the profiler!!!). That being said, you also have to include these function definitions somewhere. I personally have made them independent functions in my path, because they are super useful.
These functions and others are now available in the Functional Programming Constructs add-on which is available through the MATLAB Add-On Explorer or on the File Exchange.
How do you feel about using undocumented features:
>> builtin('_paren', magic(5), 3, 3) %# M(3,3)
ans =
13
or for cell arrays:
>> builtin('_brace', num2cell(magic(5)), 3, 3) %# C{3,3}
ans =
13
Just like magic :)
UPDATE:
Bad news, the above hack doesn't work anymore in R2015b! That's fine, it was undocumented functionality and we cannot rely on it as a supported feature :)
For those wondering where to find this type of thing, look in the folder fullfile(matlabroot,'bin','registry'). There's a bunch of XML files there that list all kinds of goodies. Be warned that calling some of these functions directly can easily crash your MATLAB session.
At least in MATLAB 2013a you can use getfield like:
a=rand(5);
getfield(a,{1,2}) % etc
to get the element at (1,2)
unfortunately syntax like magic(5)(3,3) is not supported by matlab. you need to use temporary intermediate variables. you can free up the memory after use, e.g.
tmp = magic(3);
myVar = tmp(3,3);
clear tmp
Note that if you compare running times with the standard way (asign the result and then access entries), they are exactly the same.
subs=#(M,i,j) M(i,j);
>> for nit=1:10;tic;subs(magic(100),1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0103
>> for nit=1:10,tic;M=magic(100); M(1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0101
To my opinion, the bottom line is : MATLAB does not have pointers, you have to live with it.
It could be more simple if you make a new function:
function [ element ] = getElem( matrix, index1, index2 )
element = matrix(index1, index2);
end
and then use it:
value = getElem(magic(5), 3, 3);
Your initial notation is the most concise way to do this:
M = magic(5); %create
value = M(3,3); % extract useful data
clear M; %free memory
If you are doing this in a loop you can just reassign M every time and ignore the clear statement as well.
To complement Amro's answer, you can use feval instead of builtin. There is no difference, really, unless you try to overload the operator function:
BUILTIN(...) is the same as FEVAL(...) except that it will call the
original built-in version of the function even if an overloaded one
exists (for this to work, you must never overload
BUILTIN).
>> feval('_paren', magic(5), 3, 3) % M(3,3)
ans =
13
>> feval('_brace', num2cell(magic(5)), 3, 3) % C{3,3}
ans =
13
What's interesting is that feval seems to be just a tiny bit quicker than builtin (by ~3.5%), at least in Matlab 2013b, which is weird given that feval needs to check if the function is overloaded, unlike builtin:
>> tic; for i=1:1e6, feval('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 49.904117 seconds.
>> tic; for i=1:1e6, builtin('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 51.485339 seconds.

Can someone define what a closure is in real world language? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is a ‘Closure’?
I read more and more about closures but I don't really get what it is from a practical standpoint. I read the wikipedia page on it but it doesn't really clear anything up for me because I have more of a practical background in programming (self taught) as opposed to a computer science background. If this is a reundant question, I apologize as my initial search didn't yield anything that really answered it for me.
edit: Thanks for pointing me in the right direction! I see this has already been clearly answered before so I will close the question out.
Eric Lippert's blog does a pretty good job at explaining this in a practical sense.
And so does Kyle at SO
An operation is said to be closed over a set when the result of that operation also belongs to that set.
For example - Consider a set of positive integers. Addition is a closed operation over this set because adding two positive integers would always give a positive integer.
However subtraction is not closed over this set because 2 - 3 would give -1 which does not belong to the set of positive integers.
cheers
Two one sentence summaries:
• a closure is the local variables for a function - kept alive after the function has returned, or
• a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
http://blog.morrisjohns.com/javascript_closures_for_dummies
probably best demonstrated by an example
program output (artificially) prefixed by *
Javascript:
js> function newCounter() {
var i = 0;
var counterFunction = function () {
i += 1;
return i;
}
return counterFunction;
}
js> aCounter = newCounter()
* function () {
* i += 1;
* return i;
* }
js> aCounter()
* 1
js> aCounter()
* 2
js> aCounter()
* 3
js> bCounter = newCounter()
* function () {
* i += 1;
* return i;
* }
js> bCounter()
* 1
js> aCounter()
* 4
"Real world language" is a difficult measure to gauge objectively, but I'll give it a try since after all I also lack a CS background (EE major here) and am a little self-taught;-)
In many languages, a function "sees" more than one "scope" (group) of variables -- not only its local variables, and that of the module or namespace it's in, but also (if it's within another function) the local variables of the function that contains it.
So, for example (in Python, but many other languages work similarly!):
def outer(haystack):
def inner(needle):
eldeen = needle[::-1]
return (needle in haystack) or (eldeen in haystack)
return [x for x in ['gold','silver','diamond','straw'] if inner(x)]
inner can "see" haystack without needing to see it as an argument, just because its containing function outer has haystack "in scope" (i.e. "visible"). So far, so clear, I hope -- and this isn't yet about closures, it's about lexical scoping.
Now suppose the outer function (in a language treating functions as first-class objects, and in particular allowing them to be returned as results of other functions) the outer function returns the inner one instead of just calling it internally (in Python, that's for example what usually happens when you use decorator syntax #something).
How can the inner function (returned as a result) still refer to the outer function's variable, since the outer function has finished?
The answer is exactly this "closure" business -- those variables from the outer function which the inner (returned) function may still need are preserved and attached as attributes of the inner-function object that's returned.

Resources