I am currently just trying to wrap my head around this example question. I don't understand the syntax of it. I don't understand the point of i and how it relates to result
def pow(base, exponent)
result = 1
i = 1
while i <= exponent
result = result * base
i += 1
end
result
end
Any explanation much appreciated!!
while need a do while(i <= exponent) do
i is a counter, you can replace the while for
exponent.times { result = result * base }
this code will execute the number (exponent) times the content of { }
And the result on end is the result of function, in ruby if you don't put a return clause will return the last line executed
Related
I am getting my head around the functional model in Ruby and ran into a problem. I am able to successfully pass any given number of arguments to an arbitrary function as follows:
add = ->(x, y) { return x + y }
mul = ->(x, y) { return x * y }
def call_binop(a, b, &func)
return func.call(a, b)
end
res = call_binop(2, 3, &add)
print("#{res}\n") #5
res = call_binop(3, 4, &mul)
print("#{res}\n") #12
However, I am not able to pass an arbitrary number of functions:
dbl = ->(x) { return 2 * x }
sqr = ->(x) { return x * x }
def call_funccomp(a, &func1, &func2)
return func2.call(func1.call(a))
end
res = call_funccomp(3, &dbl, &sqr)
print("#{res}\n") #Expect 36 but compiler error
The compiler error is syntax error, unexpected ',', expecting ')'
I have already added both lambdas and procs to an array and then executed elements of the array, so I know I can get around this by passing such an array as an argument, but for simple cases this seems to be a contortion for something (I hope) is legal in the language. Does Ruby actually limit the number or lambdas one can pass in the argument list? It seems to have a reasonably modern, flexible functional model (the notation is a little weird) where things can just execute via a call method.
Does Ruby actually limit the number or lambdas one can pass in the argument list?
No, you can pass as many procs / lambdas as you like. You just cannot pass them as block arguments.
Prepending the proc with & triggers Ruby's proc to block conversion, i.e. your proc becomes a block argument. And Ruby only allows at most one block argument.
Attempting to call call_funccomp(3, &dbl, &sqr) is equivalent to passing two blocks:
call_funccomp(3) { 2 * x } { x * x }
something that Ruby doesn't allow.
The fix is to omit &, i.e. to pass the procs / lambdas as positional arguments:
dbl = ->(x) { 2 * x }
sqr = ->(x) { x * x }
def call_funccomp(a, func1, func2)
func2.call(func1.call(a))
end
res = call_funccomp(3, dbl, sqr)
print("#{res}\n")
There's also Proc#>> which combines two procs:
def call_funccomp(a, func1, func2)
(func1 >> func2).call(a)
end
I am trying to check if there is a space in an input line.
I have indexed the input but I got an error: "Expected ';' expected ')' "
string mike20;
int count = 0;
while (getline(cin, mike20))
for (mike20[0]); (isspace(mike20[0]); ++mike20[0])
return 0;
Firstly they are syntax error in your code, it is more like that for (mike20[0]; isspace(mike20[0]); ++mike20[0]). Secondly you seem don't understand how the for loop work. As is nothing change, so the loop is infinite.
You need a variable to browse each char of the string and do your test on each of them.
int cursor;
for (cursor = 0; cursor < number_of_char_in_mike20; ++cursor)
{
isspace(mike20[i]);
}
this code is incomplet you need to declare and initialise the number_of_char_in_mike20 variable and the isspace() function must be define if is not.
PS: don't forget braces {} for while loop and for loop, without only the first instruction is repeated.
for (initialisation(only once); test(each time); increment(each time))
first_instruction; // each time
second_instruction; // after the loop end
third_instruction; // after the loop end
fourth_instruction; // after the loop end
fifth_instruction; // after the loop end
for (initialisation(only once); test(each time); increment(each time))
{
first_instruction; // each time
second_instruction; // each time
third_instruction; // each time
}
fourth_instruction; // after the loop end
fifth_instruction; // after the loop end
I'm trying to write a method which will allow me to print out positions of a chess game for the top 8 positions.
I have a val mutable initial which is an array of 32 entries,each containing chesspiece * chesscolor * chessposition.
The chessposition is defined as:
chess_position = Alive of chessletter * int | Dead;;
Im trying to print out the positions on the first row of the board for now.
I have the following code:
class chess =
object
val mutable initial = ([|Rook,Black,Alive(A,8); (*... *)|])
method print =
for i = 0 to i = 7 do
for j = 0 to j = 32 do
if initial.(j) = (Pawn,White,Alive(A,i)) then tmp1="P" else
if initial.(j) = (Pawn,Black,Alive(A,i)) then tmp1="p" else
if initial.(j) = (Rook,White,Alive(A,i)) then tmp1="R" else
if initial.(j) = (Rook,Black,Alive(A,i)) then tmp1="r" else
if initial.(j) = (Knight,White,Alive(A,i)) then tmp1="N" else
if initial.(j) = (Knight,Black,Alive(A,i)) then tmp1="n" else
if initial.(j) = (Bishop,White,Alive(A,i)) then tmp1="B" else
if initial.(j) = (Bishop,Black,Alive(A,i)) then tmp1="b" else
if initial.(j) = (Queen,White,Alive(A,i)) then tmp1="Q" else
if initial.(j) = (Queen,Black,Alive(A,i)) then tmp1="q" else
if initial.(j) = (King,White,Alive(A,i)) then tmp1="K" else
if initial.(j) = (King,Black,Alive(A,i)) then tmp1="k" else
tmp1=".";
print_string tmp1;
done
done
end
In the case of normal chess starting positions where the row is white,this should print out:
RNBQKBNR
I'm getting an error of unbound value i and i cant understand why.
On a side note,any advice on classes and methods is appreciated since i'm trying to learn this and currently suck at it.
This line:
for i = 0 to i = 7 do
is not legitimate. It parses as this:
for i = 0 to (i = 7) do
The second expression compares i against 7 for equality. But at that point there is no i defined yet. i is only defined in the body of the for loop.
You want to say:
for i = 1 to 7 do
Anyone on ideas on a more efficient solution than the if else function below?? This takes the bulk of the time for the code so I need to reduce it.
The full function is
function result = vre(t,r,e,n,d)
if (e==4 && r>0)
result = 0;
elseif (e==4 && r==0)
result = 1;
elseif (e<4 && r==1)
result = t;
elseif (e<4 && r==2)
result = d;
else
result=n;
end
end
If this function is taking most of your processing time, it is almost certainly because you're calling it too many times. In turn, this is likely because you are calling it on each element of a vector or matrix individually. I suggest changing the function to accept matrix inputs for e and r, so you can perform all the checks at once - matlab is built for matrix operations, so taking advantage of those is always a good idea.
function result = vre(t,r,e,n,d)
#% add error checking for size of input args if desired
result = ones(size(e))*n; #% default result; next assign special cases
result(e==4 & r>0) = 0; #% note the single & for element-wise 'and'
result(e==4 & r==0) = 1;
result(e<4 & r==1) = t;
result(e<4 & r==2) = d;
end
The function now returns a matrix that is the same size as the input matrices - for single elements it will work exactly the same as your current version, but for higher dimensional inputs it will work too, and probably give you a substantial speed boost.
function result = vre(t,r,e,n,d)
if (e==4) {
if(r>0)
result = 0;
elseif (r==0)
result = 1;
}
elseif (e<4) {
if(r==1)
result = t;
elseif (r==2)
result = d;
}
else
result=n;
end
end
By doing it this way you'll only verify (e==4) and (e<4) once, avoiding unnecessary verifications.
Hope it saves some processing time.
PS: Not tested since I don't have MatLab installed.
Try this:
function result = vre(t,r,e,n,d)
if (e==4)
result = (r==0);
elseif (e<4)
result = (r==1)*t+(r==2)*d;
else
result=n;
end
end
I can't guarantee that it's more efficient (I use octave rather than matlab, so speed testing isn't going to help). But I think it will be.
Hello I've been trying to get this code to work, I even cheated and added in the goal to my code and its still not accepting my answer, any suggestions?
-- Functions...
function p() -- For user imput..
print("Enter # and try to get the closest to it! (Valid range is 1-100)")
local var = tonumber(io.read())
if var == nil then
var = 0
end
return var
end
--Start main code..
-- Initialize the pseudo random number generator (I'm on windows...)
math.randomseed( os.time() )
math.random(); math.random(); math.random()
-- Setting goal
goal = math.random(1,100)
-- Guessing loop...
repeat
g = p()
print(g)
print(goal)
until g == Goal
print("YOU GUESSED THE GOAL!")
Replace the G by a lower case g.
until g == goal