I'm a beginner at TCL and while trying to build the GCD algorithm I ran into some problems I'd like some help with:
how can I call a proc inside a proc recursively like so
proc Stein_GCD { { u 0 } { v 0 } } {
if { $v == 0 } {
puts "$u\t\t$v\t\t$v"
}
if { [expr { $v % 2 } && { $u % 2 } ] == 0 } {
return [expr 2 * ${Stein_GCD 1 0} ]
}
}
set a [Stein_GCD 2 2 ]
puts $a
as you can see, I made the proc to evaluate GCD(the code does not make any sense because I'm trying to solve an example issue), and I'm trying to recursively call the proc again to continue evaluating(notice that I made an if statement that can understand the Stein_GCD 1 0 call, yet the tcl 8.6.6 online EDA emulator says:
can't read "Stein_GCD 1 0": no such variable
while executing
"expr 2 * ${Stein_GCD 1 0} "
(procedure "Stein_GCD" line 5)
invoked from within
"Stein_GCD 2 2 "
invoked from within
"set a [Stein_GCD 2 2 ]"
(file "main.tcl" line 7)
Can you tell me how to efficiently recursively call a proc, and where was my mistake?
will gladly provide more info in the case I did a bad job at explaining.
The error can't read "Stein_GCD 1 0": indicates that you are treating the data as a single string instead of separate arguments. The problem line:
return [expr 2 * ${Stein_GCD 1 0} ]
is not written correctly. ${Stean_GCD 1 0} is not a variable.
You should have:
return [expr 2 * [Stein_GCD 1 0] ]
You want the result from Stein_GCD 1 0, so the brackets should be used.
Related
I am trying to extract an integer value from R console by asking the user the question: "How many dice do you want to save?". The user can only choose a number between 1 to 5.
Following is my code snippet:
# .... previous steps to roll 5 dices and print output
cat("Player ", player_start, ":\nDice after 1 roll(s):\n", x, "\nHow many dice do you want to save?")
number_saved_dices <- scan()
#if number_saved_dices out of the range, stop the function
if(number_saved_dices > 5 || number_saved_dices < 0 ) {
stop("You can only save between 0 and 5 dices. Try again:")
} else if(number_saved_dices == 5 ) {
#if player wants to save all five
print("For which category should the result be used?")
} else if( 0< number_saved_dices < 5 ) {
print("Please enter the values of the dice to save.")
}
For example, if the user wants to save 12 dices, then the script should be stopped with the error message "You can only save between 0 and 5 dices. Try again. " However, I can't perform if-else control flow with the number_saved_dices.
I would appreciate any help or insight!!
Thanks very much in advance!
This question already has an answer here:
if {...} else {...} : Does the line break between "}" and "else" really matters?
(1 answer)
Closed 1 year ago.
It works, but I wonder why tis is correct
if (one_time_cost_year_zero != 0) { EIW_TPI_flag = 1
} else {EIW_TPI_flag = 0}
while this results in an error
if (one_time_cost_year_zero != 0) { EIW_TPI_flag = 1 }
else {EIW_TPI_flag = 0}
What's the logic behind that?
Because R would not know that your if -else statement is not finished yet (since only the if () line is also valid R...) compare
1 + 2
+ 3
vs
1 + 2 +
3
In R if we want to split a command over multiple lines we need to either leave a bracket open (as in the if -else example) or have a "hanging" operator at the end of the line (there are also "multiline" strings, but they are not really commands per se)....
Then, the error you are seeing results from the fact that we can't beginn a command with else (like we can't start a command with in, | etc.)
Accordingly, we could also write:
if (one_time_cost_year_zero != 0) { EIW_TPI_flag = 1 } else
{EIW_TPI_flag = 0}
I am writting a simple "proc" to calculate the factorial. I would like to understand why my function does not work without the return statement.
According to TCL docs, functions that are defined without explicit "return",
return the value of the last executed command in its body.
proc fac { n } {
if { $n == 1 } {
return 1
}
puts $n
set n [expr {$n - 1}]
return [expr {[fac $n ] * $n}]
}
puts [fac 5] # ans 24
When the "return" is removed, I get the following error message:
invalid command name "1"
while executing
"[expr {[fac $n ] * $n}] "
(procedure "fac" line 7)
invoked from within
I expected that without the explicit "return", the function should return 24 as well.
Your expectation is correct. But you have square brackets around expr procedure in the last line. It is:
[expr {[fac $n] * $n}]
This means for the interpreter: 1) execute expr procedure with given argument; 2) execute the result of expr procedure. Because of this, the interpreter tries to execute procedure 1 that doesn't exist and you receive an error.
To fix this error - just remove square brackets from the last line:
proc fac { n } {
if { $n == 1 } {
return 1
}
puts $n
set n [expr {$n - 1}]
expr {[fac $n ] * $n}
}
I am a Phd student in the university of Padua and I am trying to write a little script (the first!) in R cran v. 3.0.1 to make a simulation on epidemiology.
I'd like to change the values of a vector of 883 values basing on a neighbour matrix constructed with nb2mat from a shapefile: if i and j (two cells) are neighbour (matrix) and i or j have a positive value in the vector, I'd like to transform the value of both i and j to 1 (positive), otherwise the value of i and j should remain 0. When I launch the next little script:
for(i in 1:883)
{ for(j in 1:883)
{ if(MatriceDist[i,j] > 0 & ((vectorID[i] > 0 | vectorID[j] > 0)) {
vectorID[i] = 1 & vectorID[j] = 1
print(vectorID)
} } }
the answer from the software is:
Error: unexpected '{' in:
" { for(j in 1:883)
{ while(MatriceDist[i,j] > 0 & ((vectorID[i] > 0 | vectorID[j] > 0)) {"
I think that it is an error in the statement for if but I can not understand how to solve it...
Thank you everyone!
Elisa
check your brackets :-)
for(i in 1:883) {
for(j in 1:883) {
if(MatriceDist[i,j] > 0 & (vectorID[i] > 0 | vectorID[j] > 0)) { vectorID[i] = 1 & vectorID[j] = 1 print(vectorID)
}
}
}
you had one ( to mucch before vectorID in your if statement.
please double check is the condition now specified in the statement is still the one you require.
btw: for loops are very slow in R. If you know the end size of vectorID, try pre-allocating the full matrix. That will speed things up a little bit.
I am new to groovy and I am writing a program for reading numbers from an input file which has the following format
1
2 3
4 5 6
7 8 9 10
I wish to store them in a 2D array, how would I achieve it?
I have the following code so far for the read method
private read(fileName){
def count = 0
def fname = new File(fileName)
if (!fname.exists())
println "File Not Found"
else{
def input = []
def inc = 0
fname.eachLine {line->
def arr = line.split(" ")
def list = []
for (i in 1..arr.length-1) {
list.add(arr[i].toInteger())
}
input.add(list)//not sure if this is correct
inc++
}
input.each {
print it
//not sure how to reference the list
}
}
}
I am able to print the lists but I am not sure how to use the list of lists in the program (for performing other operations on it). Can anyone please help me out here?
On the input.each all you need is to iterate again in each item in the row. If it were a collection of unknown depth, then you'd need to stick to a recursive method.
Made a small change and removed the inc, since it is not needed (at least in the snippet):
fname = """1
2 3
4 5 6
7 8 9 10"""
def input = []
fname.eachLine { line->
def array = line.split(" ")
def list = []
for (item in array) {
list.add item.toInteger()
}
input.add list
}
input.each { line ->
print "items in line: "
for (item in line) {
print "$item "
}
println ""
}
Prints:
items in line: 1
items in line: 2 3
items in line: 4 5 6
items in line: 7 8 9 10
That is plain simple iteration. You can use #Tim's suggestion to make it more idiomatic in Groovy :-)