Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
What's the proper way to call a function in PowerShell?
Example 1:
Function Divide
{
Return ($a / $b)
}
Function GetNumbers
{
$a = Read-Host "Dividend"
$b = Read-Host "Divisor"
Divide
}
GetNumbers
Example 2:
Function Divide
{
Param
(
[Int]$Dividend,
[Int]$Divisor
)
Return ($Dividend / $Divisor)
}
Function GetNumbers
{
$a = Read-Host "Dividend"
$b = Read-Host "Divisor"
Divide -Dividend $a -Divisor $b
}
GetNumbers
I mean, why should I use the Param part when I can access the parent function's variables? Or is that just bad programming?
The problem with the first example is that your Divide function will only work if it happens to be inside the GetNumbers function. If you try to call it outside of GetNumbers, you will raise an error because $a and $b will be undefined:
PS > Divide
Attempted to divide by zero.
At line:3 char:12
+ Return ($a / $b)
+ ~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
This means the use case of your Divide function is very limited and also somewhat unintuitive. People may call the function thinking it will work (since it is at module-level) and be surprised by the results.
The Divide function in the second example however does not have this issue. It is independent of the GetNumbers function and can be used anywhere a normal function can. This has three advantages:
Divide behaves as a module-level function should, which means there are no nasty surprises for your users.
The use case of Divide has been greatly enhanced. You can now divide two numbers anywhere you need to.
Your code is more robust. Divide does not need to be inside a function which just happens to define two variables named $a and $b which just happen to be numbers (see how fragile the first example is?).
Note too that you do not need to explicitly give the parameter names in your second example. You could just do:
Divide $a $b
And if you dislike the size of the second Divide function, you could always make your Param statement less spread out:
Function Divide
{
Param ([Int]$Dividend, [Int]$Divisor)
Return ($Dividend / $Divisor)
}
Related
i am new to tcl , i am trying to get the max element in a given list
i wrote a function that prints the max but it is not working properly
here is the code
proc findmax { items } {
set max 1
foreach i $items {
if { $i > $max } {
set $max $i
}
}
puts "max is = $max"
}
and i called the function like this :
findmax $items
this is the list i passed :
set items { 12 2 5 4 2 6 7 55 8 9 6 4}
but it outputs 1 and not 55 as expected
Your problem is this line:
set $max $i
In Tcl, the $ character means read from the named variable and use that value as (possibly part of) the argument to a command. It means this always. No exceptions (unless backslash-quoted or in {braces}, of course). Thus, on the first iteration of the loop you're getting (after substitution):
set 1 12
The variable name 1 is legal, but unusual and not what you want. For the algorithm to work, you instead want to give the set command the name of the variable to set, max, resulting in this:
set max $i
which will be substituted to this on the first iteration:
set max 12
That looks right! A good rule of thumb for future programming is that if a command manipulates a variable (setting it or updating it) then you need to pass the name of the variable, not the value retrieved from it.
The standard method of getting the maximum value of a list is a one-liner:
set max [tcl::mathfunc::max {*}$items]
This uses the built-in function max (which is in the ::tcl::mathfunc namespace) and passes the contents of the list in items as multiple arguments, all as one step. The {*}$ sequence is a combination of the variable-read syntax rule with the list-expansion rule, which you've probably not really thought about yet. However it's still a good exercise to write your own maximum finder as a learning exercise.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a very basic question related to boolean logic.
I have two boolean flags- flagA and flagB. I need to calculate flagC based on the values of flagA and flagB.
The code/rules are:
if($flagA && $flagB) {
$flagC = true;
} else if (!$flagA || !$flagB) {
$flagC = false;
} else if(!$flagA && !$flagB) {
$flagC = true;
}
These rules match with the XNOR truth table - http://en.wikipedia.org/wiki/XNOR_gate
I want to find out different ways to re-write the above code(if possible) with:
fewer lines of code
better performance (even if it is a minute difference)
using bit shifting?
The languages I am hoping to write this in - php, ruby/ruby on rails.
Any help/pointers will be great!
Thanks!
Don't use these languages much but this might work:
$flagC = ($flagA == $flagB);
From the link posted: http://en.wikipedia.org/wiki/XNOR_gate
two-input version implements logical equality, behaving according to the truth table to the right. A HIGH output (1) results if both of the inputs to the gate are the same. If one but not both inputs are HIGH (1), a LOW output (0) results.
So flagC is true when flagA equals flagB.
if($flagA && $flagB) {
$flagC = true;
} else {
$flagC = false;
}
(Your second rule covers all other cases.)
This question already exists:
Closed 10 years ago.
Possible Duplicate:
How can I use function callback ('StopFcn' , 'TimerFcn' )for audiorecorder object in MATLAB?
So I try to this code.
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'samples{k} = getaudiodata(r);';
r.TimerFcn = {#get_pitch,samples{k},winsize,winshift};
while 1
record(r,T);
k=k+1;
end
I want to execute the function 'get_pitch(samples,fs,winsize,winshift)' while during recording through audiorecorder object.
But following exception occurs during execution.
1) after record(r,T) is executed. (StopFcn is now called) ??? Error using ==> eval Undefined function or variable 'r'.
2) after StopFcn is called (TimerFcn is now called) In this phase, get_pitch function have totally wrong parameters. For example, parameter in the position samples{k} change to 'audiorecorder object'.
It seems that I do not know exact use of 'StopFcn' & 'TimerFcn'.
Is there anyone who can give me some advice? I really appreciate all of your comments.
Looking at the example in the documentation I would recommend trying to call getaudiodata(r) in your loop rather than with the CallBack. So something like this:
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'disp(''Completed sample '', k)';
r.TimerFcn = {#get_pitch,samples{k - 1},winsize,winshift};
while 1
record(r,T);
samples{k} = getaudiodata(r);
k=k+1;
end
Note I changed the r.TimerFcn to use samples{k - 1} instead of k because k will increment before the timerfcn gets called. So this might give you issues with your first sample, you'll have to tweak it a little. Also this is an infinite loop, which I'm sure you'll want to address.
I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.
I'm trying to split an HTML document into its head and body:
my #contentsArray = split( /<\/head>/is, $fileContents, 1);
if( scalar #contentsArray == 2 ){
$bodyContents = $dbh->quote(trim($contentsArray[1]));
$headContents = $dbh->quote(trim($contentsArray[0]) . "</head>");
}
is what i have. $fileContents contains the HTML code. When I run this, it doesn't split. Any one know why?
The third parameter to split is how many results to produce, so if you want to apply the expression only once, you would pass 2.
Note that this does actually limit the number of times the pattern is used to split the string (to one fewer than the number passed), not just limit the number of results returned, so this:
print join ":", split /,/, "a,b,c", 2;
outputs:
a:b,c
not:
a:b
sorry, figured it out. Thought the 1 was how many times it would find the expression not limit the results. Changed to 2 and works.