get in Object 'Func with Refinement in Rebol - rebol

Let's say I have
o: context [
f: func[message /refine message2][
print [message]
if refine [print message 2]
]
]
I can call it like this
do get in o 'f "hello"
But how can I do for the refinement ? something like this that would work
>> do get in o 'f/refine "hello" "world"
** Script Error: in expected word argument of type: any-word
** Near: do get in o 'f/refine
>>

I don't know if there's a way to directly tell the interpreter to use a refinement in invoking a function value. That would require some parameterization of do when its argument is a function! Nothing like that seems to exist...but maybe it's hidden somewhere else.
The only way I know to use a refinement is with a path. To make it clear, I'll first use a temporary word:
>> fword: get in o 'f
>> do compose [(to-path [fword refine]) "hello" "world"]
hello
world
What that second statement evaluates to after the compose is:
do [fword/refine "hello" "world"]
You can actually put function values into paths too. It gets rid of the need for the intermediary:
>> do compose [(to-path compose [(get in o 'f) refine]) "hello" "world"]
hello
world
P.S. you have an extra space between message and 2 above, where it should just be message2

Do this:
o/('f)/refine "hello" "world"
Parens in a path expression are evaluated if they correspond to object field or series pick/poke index references. That makes the above code equivalent to this:
apply get in o 'f ["hello" true "world"]
Note that apply arguments are positional, so you need to know the order the arguments were declared in. You can't do that trick with the function refinements themselves, so you have to use apply or create path expressions to evaluate if you want to parameterize the refinements of the function call.

Use the simple path o/f/refine

Related

How can I pass around a function with args, in red?

How can I pass a function as an argument in red?
Or would I not need that in red?
Using does I can define a function "with no arguments or local variables"
f: does [print 1] do f
>> 1
How can I make this work with (multiple) args? does is no the way, what is?
I want something like: (the following does NOT work):
; does NOT work
f: does-with-args [x][print x] do f 23
>> 1
In the last paragraph of this article http://blog.revolucent.net/2009/05/javascript-rebol.html the author says "allow functions to be passed as arguments" so I got excited, but it's also just using does :). But I learned it's possible.
How can I pass a function as an argument in red?
It doesn't seem this is the essence of your question, but you can pass a function as an argument in a couple of ways:
my-func: func [their-func [any-function!]][their-func "Stuff"]
my-func :print
my-func func [thing][probe uppercase thing]
How can I make this work with (multiple) args?
There are two possibilities here. One is APPLY:
my-func: func [thing][print uppercase thing]
apply :my-func ["Foo"]
Another is to build up a block and DO it:
do collect [keep 'my-func keep "Bar"]
do collect [keep :my-func keep "Baz"] ; keeps the function itself
NB: APPLY can be quirky and I don't think is in Red as yet, worth experimenting.

Variable substitution within braces in Tcl

Correct me wherever I am wrong.
When we use the variables inside braces, the value won't be replaced during evaluation and simply passed on as an argument to the procedure/command. (Yes, some exception are there like expr {$x+$y}).
Consider the following scenarios,
Scenario 1
% set a 10
10
% if {$a==10} {puts "value is $a"}
value is 10
% if "$a==10" "puts \"value is $a\""
value is 10
Scenario 2
% proc x {} {
set c 10
uplevel {set val $c}
}
%
% proc y {} {
set c 10
uplevel "set val $c"
}
% x
can't read "c": no such variable
% y
10
% set val
10
%
In both of the scenarios, we can see that the variable substitution is performed on the body of the if loop (i.e. {puts "value is $a"}), whereas in the uplevel, it is not (i.e. {set val $c}), based on the current context.
I can see it as if like they might have access it via upvar kind of stuffs may be. But, why it has to be different among places ? Behind the scene, why it has to be designed in such this way ? Or is it just a conventional way how Tcl works?
Tcl always works exactly the same way with exactly one level of interpretation, though there are some cases where there is a second level because a command specifically requests it. The way it works is that stuff inside braces is never interpolated or checked for word boundaries (provided those braces start at the start of a “word”), stuff in double quotes is interpolated but not parsed for word boundaries (provided they start a word), and otherwise both interpolation and word boundary scanning are done (with the results of interpolation not scanned).
But some commands send the resulting word through again. For example:
eval {
puts "this is an example with your path: $env(PATH)"
}
The rule applies to the outer eval, but that concatenates its arguments and then sends the results into Tcl again. if does something similar with its body script except there's no concatenation, and instead there's conditional execution. proc also does the same, except it delays running the code until you call the procedure. The expr command is like eval, except that sends the script into the expression evaluation engine, which is really a separate little language. The if command also uses the expression engine (as do while and for). The expression language understands $var (and […]) as well.
So what happens if you do this?
set x [expr $x + $y]
Well, first we parse the first word out, set, then x, then with the third word we start a command substitution, which recursively enters the parser until the matching ] is found. With the inner expr, we first parse expr, then $x (reading the x variable), then +, then $y. Now the expr command is invoked with three arguments; it concatenates the values with spaces between them and sends the result of the concatenation into the expression engine. If you had x previously containing $ab and y containing [kaboom], the expression to evaluate will be actually:
$ab + [kaboom]
which will probably give you an error about a non-existing variable or command. On the other hand, if you did expr {$x + $y} with the braces, you'll get an addition applied to the contents of the two variables (still an error in this case, because neither looks like a number).
You're recommended to brace your expressions because then the expression that you write is the expression that will be evaluated. Otherwise, you can get all sorts of “unexpected” behaviours. Here's a mild example:
set x {12 + 34}
puts [expr $x]
set y {56 + 78}
puts [expr $y]
puts [expr $x * $y]
Remember, Tcl always works the same way. No special cases. Anything that looks like a special cases is just a command that implements a little language (often by calling recursively back into Tcl or the expression engine).
In addition to Donal Fellows's answer:
In scenario 2, in x the command uplevel {set val $c} is invoked, and fails because there is no such variable at the caller's level.
In y, the equivalent of uplevel {set val 10} is invoked (because the value of c is substituted when the command is interpreted). This script can be evaluated at the caller's level since it doesn't depend on any variables there. Instead, it creates the variable val at that level.
It has been designed this way because it gives the programmer more choices. If we want to avoid evaluation when a command is prepared for execution (knowing that the command we invoke may still evaluate our variables as it executes), we brace our arguments. If we want evaluation to happend during command preparation, we use double quotes (or no form of quoting).
Now try this:
% set c 30
30
% x
30
% y
10
If there is such a variable at the caller's level, x is a useful command for setting the variable val to the value of c, while y is a useful command for setting the variable val to the value encapsulated inside y.

The right way to print a collection with delimiter in SmallTalk - Squeak?

I have been trying to redefine the printOn method by using this code:
coordinates do: [:elem | aStream print: elem] separatedBy: [aStream print: ' ,']
where "coordinates" stands for the name of the collection (OrderedCollection), but i was expecting to print this when calling to Transcript show:
(2/2) ,(1/1) ,(3/3) ,(-4/4)
I got this instead:
(2/2)','(1/1)','(3/3)','(-4/4)
i. e the quotes was printed as well.
I have tried to play with it, defining a local variable and use it, etc.
Nothing worked.
Don't use #print: to print strings. Use #nextPutAll: to be safe (works for all collections). #print: writes a string representation on the stream and surrounds the argument with quotes, that's why you get quotes in the output.

How to pass functions as parameters in REBOL

I have attempted to pass a function as a parameter in the REBOL programming language, but I haven't figured out the correct syntax yet:
doSomething: func [a b] [
a b
a b
]
doSomething print "hello" {This should pass print as the first argument and "hello" as the second argument.}
This produces an error, since the print function is being called instead of being passed:
hello
*** ERROR
** Script error: doSomething does not allow unset! for its a argument
** Where: try do either either either -apply-
** Near: try load/all join %/users/try-REBOL/data/ system/script/args...
Is it possible to pass the print function as a parameter instead of calling the print function?
I've found the solution: I only need to add : before the name of the function that is being passed as a parameter.
Here, the :print function is being passed as a parameter instead of being invoked with "hello" as its argument:
doSomething: func [a b] [
a b
a b
]
doSomething :print "hello" {This should pass print as the first argument and "hello" as the second argument.}
You have discovered that by the nature of the system, when the interpreter comes across a WORD! symbol type which has been bound to a function, it will invoke the function by default. The default interpreter seeing a GET-WORD! symbol type, on the other hand, suppresses invocation and just returns the value the word is bound to.
The evaluator logic is actually rather straightforward for how it reacts when it sees a certain symbol type. Another way of suppressing invocation is the single quote, which will give you a LIT-WORD! symbol... but these become evaluated as the corresponding WORD! when it sees them:
>> some-word: 'print
>> type? some-word
== word!
In fact, the behavior of a GET-WORD! when the evaluator sees it is equivalent to using the GET function with a WORD!
doSomething: func [a b] [
a b
a b
]
doSomething get 'print "hello" {Message}
The interpreter sees the LIT-WORD! 'print and evaluates that into the WORD! for print, which is then passed to GET, which gives you a FUNCTION! back.
Simplicity of the interpreter logic is why you get things like:
>> a: b: c: 10 print [a b c]
10 10 10
Due to the nature of how it handles a SET-WORD! symbol followed by complete expressions. That yields also the following code printing out 20:
if 10 < a: 20 [
print a
]
Other languages achieve such features with specialized constructs (like multiple initialization, etc.) But Rebol's logic is simpler.
Just wanted to elaborate a bit to help explain what you were looking at. My answer to this other question might provide some more insight into the edge cases, historical and future: "When I use error? and try, err need a value"

How to print multiple outputs in Smalltalk

|X Y A B C D|
Y:= 7.
X:= 6.
(X = Y)
ifTrue: [X := 0]
ifFalse:[X := 1].
B:=2.
C:=5.
D:=1.
A:= (B squared)*(C-D).
"print both A and X to screen here"
Simple enough little smalltalk example. I'm just curious how I can get this to print X and A as outputs? is there any way to do it w/o having to perform a 'print it' on the top 6 lines and a seperate 'print it' on the bottom 5 lines? if it could print out on just a 'do it' or a single 'print it' please let me know!
You should define what is "printing" and what is X and A.
If "printing" is a result of the "print it" action, then you are talking in general about returning X and A, as "print it" prints the return result of the selected code. This way you have to think about an object which will represent X and A. For this object you can define a printString method or printOn: and get the result printed. Or you can cheat a bit and return a point by doing X#A.
If you are talking about actually printing the thing somewhere then you have to tell more about where do you want to do it. You can print it in Transcript or similar, but there you have to explicitly send a message to the Transcript with what you want to be printed.
Now if you want to use this for "debugging/testing" reasons, it can be easier to go with "inspect it". In your code you can send inspect messages to the objects that you want to look at, and during the execution inspectors will open showing this objects.
Also I encourage you to follow conventions and make your variable names start with lowercase letter.
Smalltalk has no equivalent of print() or println() or the like, since most Smalltalk environments live in a window environment. There are ways to write output to stdout or std error, but this is very dialect specific.
One of the places that somehow replaces stdout in most dialects is a place/stream/window called Transcript, in most dialects this is the window that launches first when your start the IDE.
To write something there you simple do:
Transcript show: 'A=', A asString, ' ; X=', X asString.
(please note that in Smalltalk, Strings and Collections are concatenated with a comma)
You can also write a newLine by sending the message cr to the Transcript like so:
Transcript cr.
Does this answer your question?
A hint for further learning/investigation: Transcript is just a Variable that holds a Stream object. show: is a message that writes some String onto that Stream. asString is a method that returns a String representation of an object.