For some reason, the Maple code
testproc := proc()
LOCAL abc;
abc[1] := 123;
print(eval(parse(cat("abc[", 1, "]"))))
end proc
testproc();
produces
abc_1
whereas (same, but with abc now a GLOBAL variable)
testproc := proc()
GLOBAL abc;
abc[1] := 123;
print(eval(parse(cat("abc[", 1, "]"))))
end proc
produces (what I want)
123
What do I need to do so that I can evaluate a concatenated string involving a local variable? Many thanks for any help! :)
When you use parse, it operates as if the text was in its own file or entered at the top level. It doesn't have the context of lexically scoped variables.
You could do something like
eval(parse(cat("abc[",1,"]")),convert('abc',`global`)='abc');
If you want to handle multiple locals, use a set for the second argument to eval.
I assume you have some reason for going through the string form. For straight object manipulation, it isn't usually a good idea.
Related
I got a great surprise when I noticed the following snippet not compiling:
aTime := time.Time{}
if defaultTime := time.Time{} ; aTime != defaultTime {}
The compiler returns:
type time.Time is not an expression
defaultTime := time.Time used as
value undefined: defaultTime
The intent here is to test the aTime variable if it's set to it's default value.
It also does not compile if I get the pointer of the struct (defaultTime := &time.Time{}).
However, it does compile if I init defaultTime outside of the if construct, or do the init using the new() builtin:
aTime := time.Time{}
if defaultTime := new(time.Time) ; aTime != *defaultTime {}
From what I've read everywhere, new(myStruct) it supposed to be completely equivalent to &myStruct{}.
As I interprate it, defaultValue := time.Time{} qualifies as a SimpleStmt (specifically an Assignment), as detailed in the If statement spec.
I've come up with no explanation for this behavior, despite my best googling efforts. Would be grateful if someone could make my head stop spinning.
The { is recognized as the beginning of a Block, terminating the parsing of the SimpleStmt. After committing to that decision, the compiler decides that, as a SimpleStmt, aTime := time.Time isn't valid because time.Time isn't a value that can be assigned. However, it's presumably too late for the parser to try another interpretation of the {.
The version with new works because it doesn't contain a { character, and so avoids confusing the parser in this way.
You can also use the literal format by wrapping it in parentheses, because a block can't legally begin in the middle of an expression, so this also works:
if defaultTime := (time.Time{}); aTime != defaultTime {
// ...
}
gofmt gives the helpful message "expected boolean expression, found simple statement (missing parentheses around composite literal?)", but oddly, the go compiler itself does not.
I don't think what I am going to suggest is necessarily a better solution. But for your use case, you can try this to be concise
if !aTime.IsZero() {
// ...
}
Ymmv
just a short question regarding how to use TThreadList. Is it safe to use it with "with" statement as follows:
with FEngineList.DAQEngines.LockList do
begin
try
for Idx := 0 to Count - 1 do
Items[idx].Param1 := cos(2*pi*I/Count);
...
...
finally
FEngineList.DAQEngines.UnlockList;
end;
end;
or should I explicitly do it like here:
uEngines := FEngineList.DAQEngines.LockList;
try
with uEngines do
begin
for Idx := 0 to Count - 1 do
Items[idx].Param1 := cos(2*pi*I/Count);
...
...
end;
finally
FEngineList.DAQEngines.UnlockList;
end;
Thanks!
It's upon you which variant you choose. with only tells the compiler where to get members you write in your code. So yes, it is safe, as long as you're accessing members you wanted to. It doesn't affect the runtime.
I would prefer the first way, just without that begin..end block (if I'd be forced to use with), but it's just my personal preference and you are free to write it as you wish:
with FEngineList.DAQEngines.LockList do
try
...
finally
FEngineList.DAQEngines.UnlockList;
end;
Neither variant is to be recommended. If you had to choose between these two, the former is preferable since there is no real need for an extra local variable.
However, with is to be avoided. The problem is that is introduces potential for scope overlap. If the original scope and the object that is the subject of the with have members with the same name, then the with scope hides the outer scope. This catches you out when you add a new member to the subject of the with that happens to have the same name as a member of the outer scope. At best your program won't compile. At worst it compiles and you have a defect. Quite possibly a defect that you don't readily spot.
Code it like this:
uEngines := FEngineList.DAQEngines.LockList;
try
for Idx := 0 to uEngines.Count - 1 do
uEngines.[Idx].Param1 := Cos(2*pi*Idx/uEngines.Count);
....
end;
finally
FEngineList.DAQEngines.UnlockList;
end;
Related: Is Delphi "with" keyword a bad practice?
I'm trying to create string using StringOf function in code below. Why after ZeroMemory on array that was used to create string Showmessage displays nothing. Why? In commented ZeroMemory case ===== is displayed.
TIdBytes = array of Byte;
procedure fill(var b: TIDBytes);
begin
setlength(b,5);
b[0]:=61;
b[1]:=61;
b[2]:=61;
b[3]:=61;
b[4]:=61;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
POSSaleTransaction: TPOSSaleTransaction;
s: ansistring ;
b:TIDBytes;
begin
fill(b);
s := StringOf( TArray<byte>(b) );
ZeroMemory(#b, Length(b));
Showmessage(s);
end;
I'm using Delphi XE4
The reason I'm trying to ZeroMemory is that I wont to be 100% shure that newly created string is not using reference to byte[], but copyes b data. With help of ZeroMemory I'm deleting contents of b while expecting that it will not have influence on string.
ZeroMemory does not free memory. It writes zero bytes into the block of memory that you provide.
Even then, your code gets that wrong. In your code, b is a pointer to the dynamic array. You pass #b to ZeroMemory so you are zeroising the pointer rather than the array that it points to. And since the value byte count that you pass is greater than SizeOf(b) then you are zeroising other parts of the stack too. That's why your call to ZeroMemory is destroying your string.
To zeroise the memory you would write:
ZeroMemory(Pointer(b), Length(b));
If you want to delete a dynamic array then you can write
b := nil;
or
Finalize(b);
or
SetLength(b, 0);
The reason I'm trying to use ZeroMemory is that I want to be 100% sure that newly created string is not using reference to the byte array, but is a copy of it.
You don't need to write any code to prove that. You can be sure because a Delphi string is UTF-16 encoded, and your byte array uses an 8 bit encoding. So even if the RTL designers wanted to take a reference to the byte array, it would not have been possible.
You just blew the stack variables there. Both the B pointer (in its entirety) and partially the pointer S ( (Length(b) - SizeOf(b)) bytes of it ).
What is b ? it is a some complex structure, a handle, a pointer. Usually You do not want to destroy memory structure, you want to put the data into the cells. But in your example you just wiped out the whole memory structures allocated on stack. Including, probably, the string itself.
The following program works as expected in Delphi XE2 - see what is there instead of Zero Memory. Read what are dynamic arrays in Delphi and how they are allocated from CPU Assembler point of view when you want to use low-level tricks as raw pointers ( or untyped variables like in ZeroMemory)
program Project11;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
procedure fill(var b: TBytes);
begin
SetLength(b,5);
// b[0]:=61; b[1]:=61; b[2]:=61; b[3]:=61; b[4]:=61;
FillChar(b[Low(b)], Length(b), 61); // Less copy-paste, more program structure
// Notice, above i take pointer to the cell inside the array,
// not to the array the container itself.
// That is both safer and does document the intention of the code
end;
Procedure SOTest();
var
s: ansistring ;
b: TBytes;
begin
fill(b);
s := StringOf( b );
// ZeroMemory(#b, Length(b)); -- destroying the pointer instead of freeing memory - is a memory leak
// FillChar(b, Length(b), 0); -- same as above, written in Pascal style, rather than C style.
b := nil; // this really does free the DYNAMIC ARRAYS. Laconic but prone to errors if mistyped.
// SetLength(b, 0); -- more conventional and safe method to do the same: free string or dyn-array.
// Anyway that is unnecessary - both b and s would anyway be auto-freed before the function exit.
Writeln(Length(s):4, ' ', s);
end;
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
SOTest;
Write('Press Enter to exit;'); ReadLn;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
See manuals.
http://docwiki.embarcadero.com/Libraries/XE4/en/System.FillChar
http://docwiki.embarcadero.com/RADStudio/XE4/en/Parameters_(Delphi)#Untyped_Parameters
http://docwiki.embarcadero.com/RADStudio/XE4/en/Structured_Types#Dynamic_Arrays
http://docwiki.embarcadero.com/Libraries/XE4/en/System.SysUtils.TBytes
http://docwiki.embarcadero.com/Libraries/XE4/en/System.SysUtils.StringOf
So the next question is WHY were you trying to call ZeroMemory, what is the point there ? IS there soem attempt to destroy a cypher key or other sensitive data ? http://www.catb.org/~esr/faqs/smart-questions.html#goal
If you only want to assure that "s" variable does not have any external references - there is a special function for it, UniqueString.
http://docwiki.embarcadero.com/Libraries/XE4/en/System.UniqueString
However in this particular workflow and this particular Delphi version that could not happen anyway. Read again manual for StringOf - it returns a UnicodeString temporary hidden variable. That variable is encoded in UTF-16 in XE4, which means having 2 bytes per letter, which means the original byte-chain would not suit anyway and would be transformed into new buffer.
After that you convert the UnicodeString temporary hidden variable into AnsiString variable s having one byte per letter, so it also can not have references to the temp-var, but would allocate yet another independent buffer to hold the transformed data.
As you can see there is two necessary copy-with-transformation operations, both of which make keeping data references just impossible.
You probably want to do this:
ZeroMemory(#b[0], Length(b));
instead of
ZeroMemory(#b, Length(b));
Remember the b variable is 4 bytes size pointer only and point to array of bytes.
I recently had the necessity of rewriting a javascript function in javascript, dynamically. The ease with which I did it, and how fun it was, astounded me.
Over here I've got some HTML:
<div id="excelExport1234"
onclick="if(somestuff) location.href='http://server/excelExport.aspx?id=56789&something=else'; else alert('not important');"
>Click here to export to excel</div>
And I couldn't change the outputted HTML, but I needed to add an extra parameter to that link. I started thinking about it, and realized I could just do this:
excelExport = $('excelExport1234');
if (needParam)
eval('excelExport.onclick = ' + excelExport.onclick.toString().replace("excelReport.aspx?id", "excelReport.aspx?extraParam=true&id") + ';');
else
eval('excelExport.onclick = ' + excelExport.onclick.toString().replace("extraParam=true&", "") + ';');
And it worked like a champ! excelExport.onclick returns a function object which I convert to a string, and do some string manip on. Since it's now in the form of "function() { ... }", I just go back and assign it to the onclick event of the dom object. It's a little ugly having to use eval, but AFAIK there isn't a javascript function constructor that can take a string of code and turn it into an object nicely.
Anyway, my point isn't that I'm super clever (I'm not), my point is that this is cool. And I know javascript isn't the only language that can do this. I've heard that lisp has had macros for years for this exact purpose. Except to really grok macros you need to really grok lisp, and I don't grok it, I just 'kind of get it'.
So my question is: In what other languages can you (easily) dynamically rewrite functions, and can you show me a simple example? I want to see where else you can do this, and how it's done!
(also, I have no idea what to tag this as, so I took random guesses)
LISP is the ultimate language at this. LISP functions are actual LISP lists, meaning you can manipulate LISP source code as if it were any other data structure.
Here's a very trivial example of how it works:
(define hi
(lambda () (display "Hello World\n")))
;; Displays Hello World
(hi)
(set! hi
(lambda () (display "Hola World\n")))
;; Displays Hola World
(hi)
This, however, is possible in any language where functions are first-class objects. One of the most interesting showcases of the power of this syntax for LISP is in its macro system. I really don't feel I could do the topic justice, so read these links if you're interested:
http://en.wikipedia.org/wiki/Macro_(computer_science)#Lisp_macros
http://cl-cookbook.sourceforge.net/macros.html
I guess it depends on what exactly you define as "easily dynamic rewriting". For example in .Net you have the Func type and lambdas which allows you to define functions as variables or as temporary anonymous functions eg.
int[] numbers = {1, 2, 3, 4, 5};
Func<int[], int> somefunc;
if (someCondition)
{
somefunc = (is => is.Sum());
} else {
somefunc = (is => is.Count());
}
Console.WriteLine(somefunc(numbers).ToString());
The above is a very contrived example of either counting the items in an array of integers or summing then using dynamically created functions subject to some arbitrary condition.
Note - Please don't point out that these things can be easily accomplished without lambdas (which they obviously can) I was simply trying to write a very simple example to demonstrate the concept in C#
Self-modifying code is also called degenerate code. This is generally considered a bad thing, and it used to be a goal of high-level languages to prevent it from being written easily.
This is from the wikipedia entry:
Self-modifying code is seen by some as a bad practice which makes code harder to read and maintain. There are however ways in which self modification is nevertheless deemed acceptable, such as when sub routine pointers are dynamically altered - even though the effect is almost identical to direct modification.
I think that it is the case in most of dynamic languages. Here is an example in Python
def f(x):
print x
def new_function(x): print "hello", x
f("world")
f = new_function
f("world")
The output is
world
hello world
I think that such technique should be used carefully
Scheme allows you to do that.
(define (salute-english name) (display "Hello ") (display name))
(define (salute-french nom) (display "Salut ") (display nom))
Now you redefine a fonction by assigning the salute variable to the right function, either salute-english or salute-french, like this:
(define salute salute-english)
(define (redefined-the-salute-function language)
(if (eq? language 'french)
(set! salute salute-french)
(set! salute salute-english)))
More generaly functional programming language allows you to do that or as functions are first class value. Functions can be manipulated, passed around, sometimes assigned to variables and so on. The list then include: Lisp, Scheme, Dylan, OCaml and SML. Some languages having first class functions includes Python, Ruby, Smalltalk and i think Perl.
Note that when you have an interactive language where you can interactively type your program, the redefinition of functions/methods must be possible: the REPL has to be able to do that, just in case you happen to retype the definition of an already defined functions.
I used to do this all the time in TCL, it was a breeze and worked wonderfully. I could investigate somethings interface over the network and then create a custom-made interface on the fly to access and control things. For example, you could make a custom SNMP interface from a generic SNMP library.
I haven't used it, but C# has some built-in support for generating it's own byte-code, which is fairly impressive.
I've done this sort of thing in C as well, but there it is non-portable and almost never worth the hassle. It is a technique used sometimes for "self-optimizing" code to generate the appropriate C function to optimally process a given data set.
You could do it in C++, but it wouldn't be easy, safe, or recommended.
Generate the text of the source code
invoke the compiler (fork & exec) to build a dynamic library. In gcc, you can pass the source code you want to compile on standard input, it doesn't have to be in a file.
Load the library (LoadLibrary() on windows, dlopen() on linux)
get a function pointer to whatever function you want (GetProcAddress() on windows, dlsym() on linux)
If you want to replace an existing function, if it's a virtual function you could modify the v-table to point to the new function (that part especially is a horrible idea fraught with peril). The location of the v-table or the format of it isn't part of the C++ standard, but all the toolchains I've used have been consistent within themselves, so once you figure out how they do it, it probably won't break.
Easy enough in Perl.
*some_func = sub($) {
my $arg = shift;
print $arg, "\n";
};
some_func('foo');
Re Sam Saffron's request:
*hello_world = sub() {
print "oops";
};
hello_world();
*hello_world = sub() {
print "hello world";
};
hello_world();
In PLSQL:
create or replace procedure test
as
begin
execute immediate '
create or replace procedure test2
as
begin
null;
end;
';
end;
/
Here's something else in Python (in addition to luc's answer), which I am not recommending, but just to show it - there is exec, which can execute a string which you could build to be whatever code...
I/O shown here is from a Python 2.5.2 interpreter session. Just some simple examples of constructing strings to execute from substrings (>>> is the interpreter prompt)...
>>> def_string = 'def my_func'
>>> param_string_1 = '():'
>>> param_string_2 = '(x):'
>>> do_string_1 = ' print "Do whatever."'
>>> do_string_2 = ' print "Do something with", x'
>>> do_string_3 = ' print "Do whatever else."'
>>> do_string_4 = ' print "Do something else with", x'
>>> def_1 = '\n'.join([def_string+param_string_1, do_string_1, do_string_3])
>>> print def_1
def my_func():
print "Do whatever."
print "Do whatever else."
>>> exec def_1
>>> my_func()
Do whatever.
Do whatever else.
>>> def_2 = '\n'.join([def_string+param_string_2, do_string_2, do_string_4])
>>> print def_2
def my_func(x):
print "Do something with", x
print "Do something else with", x
>>> exec def_2
>>> my_func('Tom Ritter')
Do something with Tom Ritter
Do something else with Tom Ritter
>>>
Trivial in Ruby:
def hello_world; puts "oops"; end
hello_world
# oops
def hello_world; puts "hello world"; end
hello_world
# hello world
Of course that example is boring:
require "benchmark"
# why oh _why
class Object
def metaclass; class << self; self; end; end
def meta_eval &blk; metaclass.instance_eval &blk; end
end
class Turtle
end
def make_it_move(klass)
klass.send(:define_method, :move) { |distance|
puts "moving #{distance} meters"
sleep(0.1 * distance)
}
end
make_it_move(Turtle)
turtle = Turtle.new
turtle.move(1)
# moving 1 meters
def profile(instance, method)
instance.meta_eval do
m = instance_method(method)
define_method method do |*a|
puts "Benchmarking #{instance.class} #{method}"
puts Benchmark.measure {
m.bind(instance).call(*a)
}
end
end
end
profile(turtle, :move)
turtle.move(10)
# Benchmarking Turtle move
# moving 10 meters
# 0.000000 0.000000 0.000000 ( 1.000994)
Turtle.new.move(3)
# moving 3 meters
The code above:
Defines a blank class
Adds a method to it
Grabs an instance
Intercepts that method on that instance only
Changing what a function does is supported in a lot of languages, and it's not as complicated as you might think. In functional languages, functions are values, and function names are symbols that are bound to them like any variable. If the language allows you to reassign the symbol to a different function, this is trivial.
I think the more interesting features are the ability to get the source code for a function (toString above) and to create a new function from a string (eval in this case).
I am trying to compare two strings in Smalltalk, but I seem to be doing something wrong.
I keep getting this error:
Unhandled Exception: Non-boolean receiver. Proceed for truth.
stringOne := 'hello'.
stringTwo := 'hello'.
myNumber := 10.
[stringOne = stringTwo ] ifTrue:[
myNumber := 20].
Any idea what I'm doing wrong?
Try
stringOne = stringTwo
ifTrue: [myNumber := 20]`
I don't think you need square brackets in the first line
Found great explanation. Whole thing is here
In Smalltalk, booleans (ie, True or False) are objects: specifically, they're instantiations of the abstract base class Boolean, or rather of its two subclasses True and False. So every boolean has type True or False, and no actual member data. Bool has two virtual functions, ifTrue: and ifFalse:, which take as their argument a block of code. Both True and False override these functions; True's version of ifTrue: calls the code it's passed, and False's version does nothing (and vice-versa for ifFalse:). Here's an example:
a < b
ifTrue: [^'a is less than b']
ifFalse: [^'a is greater than or equal to b']
Those things in square brackets are essentially anonymous functions, by the way. Except they're objects, because everything is an object in Smalltalk. Now, what's happening there is that we call a's "<" method, with argument b; this returns a boolean. We call its ifTrue: and ifFalse: methods, passing as arguments the code we want executed in either case. The effect is the same as that of the Ruby code
if a < b then
puts "a is less than b"
else
puts "a is greater than or equal to b"
end
As others have said, it will work the way you want if you get rid of the first set of square brackets.
But to explain the problem you were running into better:
[stringOne = stringTwo ] ifTrue:[myNumber := 20]
is passing the message ifTrue: to a block, and blocks do not understand that method, only boolean objects do.
If you first evaluate the block, it will evaluate to a true object, which will then know how to respond:
[stringOne = stringTwo] value ifTrue:[myNumber := 20]
Or what you should really do, as others have pointed out:
stringOne = stringTwo ifTrue:[myNumber := 20]
both of which evaluates stringOne = stringTwo to true before sending ifTrue:[...] to it.
[stringOne = stringTwo] is a block, not a boolean. When the block is invoked, perhaps it will result in a boolean. But you are not invoking the block here. Instead, you are merely causing the block to be the receiver of ifTrue.
Instead, try:
(stringOne = stringTwo) ifTrue: [
myNumber := 20 ].
Should you be blocking the comparison? I would have thought that:
( stringOne = stringTwo ) ifTrue: [ myNumber := 20 ]
would be enough.
but I seem to be doing something wrong
Given that you are using VisualWorks your install should include a doc folder.
Look at the AppDevGuide.pdf - it has a lot of information about programming with VisualWorks and more to the point it has a lot of introductory information about Smalltalk programming.
Look through the Contents table at the beginning, until Chapter 7 "Control Structures", click "Branching" or "Conditional Tests" and you'll be taken to the appropriate section in the pdf that tells you all about Smalltalk if-then-else and gives examples that would have helped you see what you were doing wrong.
I would like to add the following 50Cent:
as blocks are actually lambdas which can be passed around, another good example would be the following method:
do:aBlock ifCondition:aCondition
... some more code ...
aCondition value ifTrue: aBlock.
... some more code ...
aBlock value
...
so the argument to ifTrue:/ifFalse: can actually come from someone else. This kind of passed-in conditions is often useful in "..ifAbsent:" or "..onError:" kind of methods.
(originally meant as a comment, but I could not get the code example to be unformatted)