Condition: positive and negative number in RPG - rpgle

When I enter a negative number in my console, I don't get the display !
For example if enter the value ´-2´, I don't get the message 'negative`
In positive and null c'est ok
H
D Number S 2S 0
*
/Free
dsply 'Enter your number please : ' '' Number;
If (Number > 0);
dsply 'Positive';
ElseIf (Number = 0);
dsply 'Null';
Else;
dsply 'Negative';
ENDIF;
*inlr = *on;
/End-Free

In the RPGLE reference for the DSPLY op-code I found this excerpt:
If a non-float numeric field is entered with a length greater than the number of digits in the result field
and the rightmost character is not a minus sign (-), an error is detected and a second wait occurs. The
user must key in the field again.
It seems the DSPLY op-code expects the minus sign to be trailing and not leading.

If you do F1 (help) on the DSPLY message, it shows this:
Message ID . . . . . . : RNQ5337 Severity . . . . . . . : 00
Message type . . . . . : Sender copy
Date sent . . . . . . : 12/18/20 Time sent . . . . . . : 12:42:16
Message . . . . : DSPLY Enter your number please : 0
Cause . . . . . : This is an inquiry message originated from RPG procedure
MY_PGM in program MY_LIB/MY_PGM. The program is expecting a numeric
input field with a maximum length of 2 digits with 0 decimal positions. Do
not type in a decimal point when entering data. When entering negative data,
type a negative sign ('-') immediately after the last digit of the data.

You can use %dec() to convert a numeric value in a string to a numeric variable. That will allow your users to place the negative sign on the left or the right. This might be a friendlier way of using the DSPLY opcode.
**FREE
//simple demo, not worrying about exceptions
dcl-s myStr varchar(5);
dcl-s myNum packed(3:0);
dsply 'Enter your number please : ' '' myStr;
myNum = %dec(myStr:3:0);
Select;
When (myNum > 0);
dsply 'Positive';
When (myNum = 0);
dsply 'Zero'; // not the same a null ;-)
Other;
dsply 'Negative';
EndSl;
*inlr = *on;
RETURN;

Related

Lua: string of specific length

local data = "here is a string"
local no = 12
foo = string.format("%50s %05d",data,no)
print(foo:len(),string.format("%q",foo))
defines foo as a string of specific length
" here is a string 00012"
However, is there an easy way to get
"here is a string 00012"
I know, that I can fill up the string data with spaces
while data:len() < 50 do data = data.." " end
Add a minus to format string %-50s to align text to the left:
foo = string.format("%-50s %05d","here is a string", 12)
print(foo:len(), foo)
Output:
56 here is a string 00012
Allowed flags:
- : left align result inside field
+ : always prefix with a sign, using + if field positive
0 : left-fill with zeroes rather than spaces
(space) : If positive, put a space where the + would have been
# : Changes the behaviour of various formats, as follows:
For octal conversion (o), prefixes the number with 0 - if necessary.
For hex conversion (x), prefixes the number with 0x
For hex conversion (X), prefixes the number with 0X
For e, E and f formats, always show the decimal point.
For g and G format, always show the decimal point, and do not truncate trailing zeroes.
The option to 'always show the decimal point' would only apply if you had the precision set to 0.

Parse Required Bandwidth out of FCC Designator in SPARQL/SPIN?

I need to parse the rather arcane FCC Emission Designator using SPARQL/SPIN from a compound string encoding to values I can easily reason over. The first task is to get the "required bandwidth" out of the designator. Here are examples of what the emission designators look like (available as xsd:string values) and the corresponding required bandwidths, manually interpreted my little old me:
16K00F3E 16.00 kHz or 16,000.0 Hz
3K00J3E 3.00 kHz or 3,000.0 Hz
1K10F1B 1.10 kHz or 1,100.0 Hz
100H00A1A 100.00 Hz
10M0G2D 10.0 MHz or 10,000,000.00 Hz
Ultimately I want to get to xsd:double values in Hz, but I'm presently stuck on the first step, getting the required bandwidth substring out of the whole emission designator string.
The regular expression ^[0-9]+[A-Z][0-9]+ does the trick for this first step. For example, this regular expression applied to the emission designator 10M0G2D matches 10M0.
The required bandwidth substring I want is, in practice, variable-length. It has a set of numbers, a letter (see below), and then another set of numbers. The letter marks the decimal point and determines the multiplier:
H - If the value is less than 1000 Hz (muliplier is 1.0)
K - 1 kHz to values less than 1000 kHz (multiplier is 1000.0)
M - 1 MHz to values less than 1000 MHz (multiplier is 1,000,000.0)
G - 1 GHz or greater (multiplier is 1,000,000,000.0)
This is followed by another letter which is outside the required bandwidth.
So, my question is, in SPARQL/SPIN, how do I get the required bandwidth substring as defined in the above regular expression parsed out of the emission designator string? I want to bind that substring to a SPARQL variable, say ?encodedRequiredBandwidth. The only use of a regular expression I see in SPARQL/SPIN is xsd:boolean REGEX (simple literal text, simple literal pattern). That's great, but I want the substring matching the regex, not a flag indicating it's in there somwhere.
Any ideas on how to get my required bandwidth substring?
Any ideas on how to to the remainder of the parsing to get to an xsd:double Hz value that I can reason over easily (e.g. do magnitude comparisons)?
Thanks.
I've found a way to work around this based on the fact that the last three characters of the emission designator are stable, fixed-width. So, I can use a combination of string functions to get the required bandwidth parsed out. The following simple query illustrates the use of the string functions:
SELECT DISTINCT *
WHERE
{
BIND("100H00F1B"^^xsd:string AS ?emissionDesignator) .
BIND(strlen(?emissionDesignator) AS ?edLength) .
BIND(substr(?emissionDesignator, ?edLength - 2, 3) AS ?useCodes) .
BIND(strbefore(?emissionDesignator, ?useCodes) AS ?encodedBandwidth) .
}
So now my encoded bandwidth substring ends up int ?encodedBandwidth.
Step one down, but my answer depends on a peculiarity of the format, the fixed width of the last 3 characters of the string. Now I need to figure out how to parse the frequency into an xsd:double value in Hz. I'll post again when/if I figure that out in case it's useful to anyone else.
I now also have ugly SPARQL code to complete the conversion of the bandwidth to an xsd:double. This is predicated on the assumption that the frequency designator occurs in the first 6 characters of the encoded bandwdith. The standard constrains the entire bandwidth field to 4 characters including the designator. However, I've seen examples extended up to 6 characters (e.g. the 100H00 shown above which could just as well been compliantly encoded as 100H)
Here's the SPARQL code self-contained example:
SELECT DISTINCT *
WHERE
{
BIND("5M75C3F"^^xsd:string AS ?emissionDesignator) .
BIND(strlen(?emissionDesignator) AS ?edLength) .
BIND(substr(?emissionDesignator, ?edLength - 2, 3) AS ?useCodes) .
BIND(strbefore(?emissionDesignator, ?useCodes) AS ?encodedBandwidth) .
# case of indicator in character position 1
{
BIND(substr(?encodedBandwidth, 1, 1) AS ?indicator) .
FILTER ((?indicator = "H") || (?indicator = "K") || (?indicator = "M") || (?indicator = "G")) .
}
UNION
# case of indicator in character position 2
{
BIND(substr(?encodedBandwidth, 2, 1) AS ?indicator) .
FILTER ((?indicator = "H") || (?indicator = "K") || (?indicator = "M") || (?indicator = "G")) .
}
UNION
# case of indicator in character position 3
{
BIND(substr(?encodedBandwidth, 3, 1) AS ?indicator) .
FILTER ((?indicator = "H") || (?indicator = "K") || (?indicator = "M") || (?indicator = "G")) .
}
UNION
# case of indicator in character position 4
{
BIND(substr(?encodedBandwidth, 4, 1) AS ?indicator) .
FILTER ((?indicator = "H") || (?indicator = "K") || (?indicator = "M") || (?indicator = "G")) .
}
UNION
# case of indicator in character position 5
{
BIND(substr(?encodedBandwidth, 5, 1) AS ?indicator) .
FILTER ((?indicator = "H") || (?indicator = "K") || (?indicator = "M") || (?indicator = "G")) .
}
UNION
# case of indicator in character position 6
{
BIND(substr(?encodedBandwidth, 6, 1) AS ?indicator) .
FILTER ((?indicator = "H") || (?indicator = "K") || (?indicator = "M") || (?indicator = "G")) .
}
VALUES (?freqIndicator ?multiplier) {
("H"^^xsd:string 1.0e0)
("K"^^xsd:string 1.0e3)
("M"^^xsd:string 1.0e6)
("G"^^xsd:string 1.0e9)
} .
FILTER (?indicator = ?freqIndicator) .
BIND (xsd:double(replace(?encodedBandwidth, ?freqIndicator, ".")) AS ?bandwidthDecimalPart) .
BIND ((?bandwidthDecimalPart * ?multiplier) AS ?bandwidthDouble ) .
}
The above gives the result shown below... with the double-precision value of the bandwidth in ?bandwidthDouble as Hz which makes subsequent reasoning convenient. Now on to handling the rest of the emission designator. Ultimately, this code will end up in SPIN constructors to do automated translation upon instantiation.

Determining Moves and Outcomes for Tic-Tac-Toe in MATLAB W/ Helper Function

Note: I am up-dating this as I go along. I add in comments to let you know if I added in code or not. Since I have no comments, I doubt anyone will get confused. And to whomever down-voted me, I'm putting in as much information as I can. Calm yourself.
That's a pretty long title, but it sums up everything I need to do for this problem. I am given a tic-tac-toe board in the form of a 3x3 cell and a string that tells me whose move it is (Player X or Player O). I need to out a 2xN cell that lists what possible moves can be made, and what the outcome of that move would be. For example, the the player is Player X and my board looks like:
{ 'x' 'o' 'x'
'o' 'x' 'o'
'o' ' ' ' ' }
Then my options are
{ 'x' 'o' 'x' {'x' 'o' 'x'
'o' 'x' 'o' 'o' 'x' 'o'
'o' 'x' ' '} 'o' ' ' 'x'}
'Your move, player O.' 'Player X Wins!' }
Blanks spots are always indicated by a space. Now for this problem, I've been given a helper function called 'moveEvaluater' that looks like this:
Helper Function Name: moveEvaluator
Helper Function Inputs (2): - (char) A 3x3 character array representing
a tic tac toe board, after a move
has been made.
- (char) A single character of the the
player that just moved.
Helper Function Outputs (1): - (char) A string indicating the outcome
of the turn.
The helper function moveEvaluator takes in a 3x3 character array of a
tic tac toe board after a move has been made, with spaces used to
represent the empty spaces on the board, and a single character of the
player who just went. This 2nd input will be a string of either 'x' or
'o'. This helper function will then output the outcome of that turn: if
it was player X's turn, then the two possible outcomes are 'Player X
Wins!' or 'Your turn, player O.' Similarly, if it was player O's turn,
then the two possible outcomes are 'Player O Wins!' or 'Your turn,
player X.'
So this basically does half my function for me. I seem to have this working thanks to Hoki :)
function[Move_Choices] = ticTacToeTurn(Board, str)
charBoard = reshape(char(Board) , 3 , 3 ) ;
PlayerSymbol = str ;
% Find the indices of possible move
Move_Choices = find(ismember(Board, ' '));
% // count them
nChoices = numel(Move_Choices) ;
% // pre-allocate output
outcome = cell(nChoices,1) ;
Options = '';
Strings = '';
% // Get outcome for each possible postition
for iSlot = 1:nChoices
PossibleBoard = charBoard ; % // copy the initial board
PossibleBoard(Move_Choices(iSlot) ) = PlayerSymbol;% // Add an 'x' at one of the empty position
disp(PossibleBoard) ; % display the currently played board / optional, just for your information
PossibleBoard = char(PossibleBoard);
outcome = moveEvaluator(PossibleBoard, str);
Strings = [Strings {outcome}];
end
for iSlot = 1:nChoices
PossibleBoard = charBoard ; % // copy the initial board
PossibleBoard(Move_Choices(iSlot) ) = PlayerSymbol;% // Add an 'x' at one of the empty position
disp(PossibleBoard) ; % display the currently played board / optional, just for your information
PossibleBoard = cellstr(PossibleBoard);
Options = [Options, {PossibleBoard}];
end
Move_Choices = [Options;Strings]; %// Here's my issue. This outputs a cell, but the cellstr function separated the x's and o's into cells of three. I need each spot to be their own cell :/
end
I just need it to fill in the one x in either slot, not both. Furthermore, I need to do is figure out how to use the helper function from here to output what the possible string options there are.
Testcases:
board1 = { 'x' 'o' 'x'
'o' 'x' 'o'
'o' ' ' ' ' }
move1 = 'x'
possibleMoves1 = ticTacToeTurn(board1,move1)
This should give be a 2x2 cell that looks like:
Cell (1,1) This is a cell inside a cell. All of the 'x' and 'o's are a separate cell
{'x''o' 'x'
'o' 'x' 'o'
'o' 'x' ' '}
Cell (2,1) looks is the string that says "Your move, Player O"
Cell (1,2) Should be
{ 'x' 'o' 'x'
'o' 'x' 'o'
'o' ' ' 'x'}
Cell (2, 2) looks is the string that says "Player X wins!'
I tried to look at the code for the evaluator function, but it's apparently a p file so I'm not too sure what to do. Any help would be appreciated :) Let me know if I missed anything. Should be all.
Ok, seeing you tried a bit by yourself I'll point you in the final direction. This is not a "function" and so it is not a direct answer to your assignment but it includes the complete resolution of the problem. You just have to repackage it into your function.
%% // Initial conditions
Board = {'x' 'o' 'x'
'o' 'x' 'o'
'o' ' ' ' ' };
charBoard = reshape( char(Board) , 3 , 3 ) ;
PlayerSymbol = 'x' ;
%% // Resolution
% // Find the indices of possible move
Move_Choices = find(ismember(Board, ' '));
% // count them
nChoices = numel(Move_Choices) ;
% // pre-allocate output
outcome = cell(nChoices,1) ;
% // Get outcome for each possible postition
for iSlot = 1:nChoices
PossibleBoard = charBoard ; % // copy the initial board
PossibleBoard( Move_Choices(iSlot) ) = PlayerSymbol ; % // Add an 'x' at one of the empty position
disp(PossibleBoard) ; % display the currently played board / optional, just for your information
outcome(iSlot) = moveEvaluator( PossibleBoard , PlayerSymbol ) ;
end
A bit of advice: Matlab is an interpreted language. This type of programming language has its pro and cons, but it is great for one thing, you can execute lines of code and directly see the result without the need for a complex debugger.
So you can try many different expressions and refine it until the output is what you are looking for. Seeing the way your initial code was organised, it looks like you could benefit a lot from that. Try to solve your problem bit by bit in the base workspace first until you get a good grasp on your problem and its solution. At this stage it will be a lot easier to put it into a function (just have to work out the input/output, but the core of the calculations is already solved).

How to convert number into string in agda?

I need to write something to convert number into string with agda. I found someone asked the way to transfer string into agda before.
Agda: parse a string with numbers
I thinked about use it backwards,
row-to-stringh : (m : ℕ) → string
row-to-stringh 0 = "0"
row-to-stringh 1 = "1"
row-to-stringh 2 = "2"
row-to-stringh 3 = "3"
row-to-stringh 4 = "4"
row-to-stringh 5 = "5"
row-to-stringh 6 = "6"
row-to-stringh 7 = "7"
row-to-stringh 8 = "8"
row-to-stringh 9 = "9"
row-to-stringh _ = ""
but it not good enough. when the number is greater than 9, it will just convert it into "", instead of "(that number)". Can someone help me with this?
If you don't want to implement this function yourself, there's a show function in the standard library.
If you want to write it yourself: the usual way of converting a number into a string is to extract the digits by repeatedly dividing with a remainder. For example (remainders are written in parens):
7214 / 10 = 721 (4)
721 / 10 = 72 (1)
72 / 10 = 7 (2)
7 / 10 = 0 (7)
You then just collect the remainders into list, reverse it and convert the digits to chars. It might be tempting to try this in Agda as well, however, you'll run into problems with termination checker.
Firstly, you'll have to convince it that divMod (that is, division with remainder - modulus) terminates. You can just hardcode the divisor into the function and convincing the termination checker becomes easy.
The hard part is showing that repeatedly dividing the number by 10 actually terminates. This will most likely involve some rather complex tricks (such as well founded recursion).
If you want to know how it's done this way, take a look at the implementation linked above. Anyways, there's a bit less efficient but much simpler way of doing this.
Let's represent digits by a list of natural numbers.
Digits = List ℕ
We would like to write a function addOne, that (as the name suggests) adds one to a number represented by a list of digits, that is:
addOne : Digits → Digits
For this, we'll use the primitive pen & paper method: add one to the least significant digit; if the result is less than 10, we are done; if it isn't, write 0 and carry the 1 to the next digit. So, here's our carry:
data Carry : Set where
+0 : Carry
+1 : Carry
And here's the function that performs the addition - the second Carry argument can be thought of as a carry from the addition of previous two digits.
ripple-carry : Digits → Carry → Digits
ripple-carry ns +0 = ?
ripple-carry [] +1 = ?
ripple-carry (n ∷ ns) +1 with suc n ≤? 9
... | yes _ = ?
... | no _ = ?
The actual implementation is an exercise - use the description given above. Just note that we store digits in reverse order (this allows for more efficient and easier implementation). For example, 123 is represented by 3 ∷ 2 ∷ 1 ∷ [] and 0 by [].
We can recover the addOne function:
addOne : Digits → Digits
addOne n = ripple-carry n +1
The rest is just plumbing.
toDigits : ℕ → Digits
toDigits zero = []
toDigits (suc n) = addOne (toDigits n)
show : ℕ → String
show 0 = "0"
show n = (fromList ∘ map convert ∘ reverse ∘ toDigits) n
where
convert : ℕ → Char
convert 0 = '0'
convert 1 = '1'
convert 2 = '2'
convert 3 = '3'
convert 4 = '4'
convert 5 = '5'
convert 6 = '6'
convert 7 = '7'
convert 8 = '8'
convert 9 = '9'
convert _ = ' ' -- Never happens.
Used modules:
open import Data.Char
open import Data.List
open import Data.Nat
open import Data.String
open import Function
open import Relation.Nullary
I did some testing and it turns out that this method is actually fairly effective (especially when compared to the function from standard library).
The algorithm presented above needs to access O(n) digits (addOne needs to access only one digit in 90% of cases, two digits in 9%, three in 0.9%, etc) for a given number n. Unless we have some faster primitive operations (such as _+_ using Haskell's Integer behind the scenes), this is about the fastest we can get - we are working with unary numbers after all.
Standard library uses repeated division mentioned above, which is also (unless my math is wrong) O(n). However, this does not count handling of proofs, which adds enormous overhead, slowing it down to halt. Let's do a comparison:
open import Data.Nat
open import Data.Nat.Show
open import Function
open import IO
main = (run ∘ putStrLn ∘ show) n
And here are times for the compiled code (using C-c C-x C-c in Emacs). show from standard library:
n time
———————————————
1000 410 ms
2000 2690 ms
3000 8640 ms
If we use show as defined above, we get:
n time
———————————————
100000 26 ms
200000 41 ms
300000 65 ms

Strrep not working in Matlab to make String into function

Hello I am new to MATLAB , I wanted to know how can I make my string into function . I want to access the function as a string from user in standard Matlab format (e.g exp(-10*X)-sin(pi*X)-2*tanh(X) ) Here X is the variable. Then I want to replace 'X' with 'low' and 'high' variables to calculate value of function at these limits. I have used 'strrep' for this purpose. I am getting the following errors
1)Undefined function or variable 'X'.
2) I cannot see whether 'X' was replaced with 'low' and 'high'.
Any help will be truly appreciated.
Below is my code.
high=input('Upper Limit of the Interval : ');
low=input('\nLower Limit of the interval : ');
usr_funct=input('Enter The Function in standard Matlab Format.\nEnter "X" for the
variable and * for multiply \n'); % Example exp(-10*X)-sin(pi*X)-2*tanh(X);
middle = (low+high)/2;
Flow =strrep(usr_funct, 'X', 'low');
Fhigh =strrep(usr_funct, 'X', 'high');
sprintf('Flow '); % This was to check if 'X' was replaced with 'low'. It is not printing anything
Use:
usr_funct=input('Enter The Function...', 's');
This will return the entered text as a MATLAB string, without evaluating expressions.
I think that you are looking for the eval function. That will evaluate a string as matlab code.
Here is an example:
str = 'exp(-10*X)-sin(pi*X)-2*tanh(X)' ; % let str be your math expression
high = 10; % Ask the user
low = -5; % Ask the user
% Now we evaluate for High and Low
X = low; % We want to evaluate for low
ResultLow = eval(str); % That will return your value for X = low
X = high; % We want to evaluate for low
ResultHigh = eval(str); % That will return your value for X = high
1) Undefined function or variable 'X'
If you look at the documentation for input, it says that by default, it evaluates the expression. You need to add a second argument of 's' for it to just save a string.
2) I cannot see whether 'X' was replace with 'low' and 'high'
You should type sprintf(Flow) instead of sprintf('Flow'). The latter will just output "Flow" onto the screen while the former will output the value of Flow.
Finally, the eval function may be of use later on when you actually want to evaluate your expression.

Resources