How does "showpage()" work in this piece of code? - if-statement

I have been learning Lua from http://www.lua.org/pil/4.3.1.html and they had this piece of code:
if line > MAXLINES then
showpage()
line = 0
end
I don't understand what "showpage()" does here. I don't know whether this is just an example of a function that had to be previously defined (and I don't know if you can actually do this with a function) or is it a library I don't know of.

showpage is not a standard Lua function. You can find any of Lua's built-in functions in the Lua reference manual.
If you don't find a function there it is user-defined. You'll learn how to define functions in chapter 5.
It is indeed necessary that showpage is defined befor you call it. Otherwise you will face an error message for calling a nil value.
You'll find that many code examples skip the definition of some variables.
if a<0 then a = 0 end
if a<b then return a else return b end
if line > MAXLINES then
showpage()
line = 0
end
In this example a, b, showpage, line and MAXLINES are all nil. All of this would cause errors as you're neither allowed to call nil values nor to compare nil values with numbers.
Not sure if the authors were lazy, wanted to reduce the page count or intended to make you to think about their code.

Related

Absolute value function Ocaml

I'm taking a look to this programming language "Ocaml" and I have some troubles because I read the official ocaml documentation but I don't uderstand how to use :
";" and ";;" and "in" specially inside the definition of functions.
This is my code :
let abs_val value : int -> int =
let abs_ret = ref 0 ;
if value >= 0
then abs_ret := value
else abs_ret := -value ;
let return : int = abs_ret
;;
print_int abs_val -12
Compiled with "ocamlc" it said :
File "first_program.ml", line 7, characters 2-4:
7 | ;;
^^
Error: Syntax error
And it sounds so weird for me because official ocaml's doc says that when function definition ends I must use ";;".
I noticed that after the definition of abs_val VisualStudio Code ,when I go on a newline, put automatically the cursor to 2 spaces on the right, not at the beginning of the line.
I'm new in ocaml so I don't know if this is common or not but for me sounds like if something is missing, and probably it is :)
P.S. : I know that an abs function already exists but I'm doing this to learn.
Update :
let abs_val value =
let abs_ret = ref 0 in
if value >= 0
then abs_ret := value
else abs_ret := -value in
let return : int = abs_ret;
;;
print_int abs_val -12
Am I closer right?
Sometimes it happens the syntax error is not here but above. Did you closed your previous function with ;; ? Also, what is this return ? Use the functional paradigm of the language. You use variables and references and force the type checking. I'm not sure how do you want to use this code but in a general way, try to let OCaml determine the type of your functions rather than telling the compiler what is the signature. Plus, your code shouldn't be using that much references. For instance the following :
let abs_val value =
if value < 0 then
-value
else
value
Will work perfectly and not mess up things with reference. If you wish to use references, I suggest you learn more about the functional paradigm of OCaml before going deeper into its imperative possibilities.
Your syntax error is a result of having let with no matching in.
This is a very common error when learning OCaml syntax. There are two separate uses of let in OCaml. At the top level of a module, you use let to define a symbol (a function or a value) that is one of the elements of the module. So in the following:
module M = struct
let f x = x * 2
end
The let defines a function named M.f.
Similarly your code uses let this way to define abs_val.
In other cases (not at the top level of a module), let is used only as part of the let ... in expression that looks like this:
let v = exp1 in exp2
This essentially defines a local variable v with the value exp1 that can be used in the body of exp2.
All your other uses of let (except the initial definition of abs_val) are of this second kind. However, none of them have in, so they are all syntactically incorrect.
You need to fix up these problems before you can make progress with this function. You can fix the first one, for example, by changing the first semicolon (;) to in.
As #SDAChess points out, you have a second problem with the return value of your function. There is no special return keyword in OCaml that's used to return the value of a function. A function in OCaml is just a set of nested function calls, and the value of the function is the value returned by the outermost call.

Difference between return 0 and -1 [closed]

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 3 years ago.
Improve this question
Can anyone please explain the difference between return 0 and -1 used in c++? I have read many articles and posts from other programmers saying that return 0 means the program is successful and -1 means the program has an error. But what I don't get is why use these statements when the compiler will generate an error if there is one in the program anyway? Please explain in detail what these statements really mean.
This has absolutely nothing to do with the compiler.
The compiler will report syntax errors.
The return codes are used to report if the program completed successfully.
("Success" depends on what the program was intended to do).
For example:
// Program SearchTerm "term to find"
int main(int argc, char* argv[])
{
bool search_successful = false;
[ ... do work ... ]
if (search_successful)
{
return 0; // The search worked.
}
else
{
return -1; // The search failed
}
}
Example usage:
SearchTerm "Microsoft"
More than 1 million results found... returned Success
SearchTerm "asldfjpu"
No results found... returned Failure
When a program reports success or failure, it can be integrated in the Scripts such as:
#!/bin/bash
if `SearchTerm "Microsoft"`; then
GetTopResults "Microsoft"
else
echo "No results found, no Top Results to retrieve"
fi
The return value of int main() is the so called exit code of the program. This is already so in C (which has no exceptions) and is there to basically tell to caller how it went. A exit code of zero means success and every other exit code (but normally one uses only positive ones) means that something went wrong. Sometimes programms will document what a certain exit code means i.e. if a file was not found or an allocation failed etc.
This is a very important part of scripting for example bash scripts, which know in this way if a called command went right or wrong. Even if your program crashes with an exception, the programm will generate an exit code (which will be non-zero). In bash you can see the exit code of the last run program with echo $?, so you can check that out for yourself.
A return is simply the value returned by any function. At the end of a function, the computer is able to accept a single value to take back with it when it returns to the rest of the program. In the case of the function int main(), with which you are probably familiar, the return value is used as an indication of the success of the program.
main() is simply the entry point of the program you are running. It's the first function called by your computer when the program starts (with some exceptions)
Theoretically, you could return any integer from main().
The only "accepted" thing is that anything that is non-zero is generally some error or fault. So a return 0; indicates success, while return -1; might indicate some kind of error. The truth is, the value returned from main() doesn't really matter, and won't affect how your program runs.
If you're asking about the value returned by main, there are two defined values that you can return: EXIT_SUCCESS and EXIT_FAILURE. Those values are defined in the header <stdlib.h> and in the header <cstdlib>. You can also return the value 0, which is equivalent to returning EXIT_SUCCESS. There are no other meaningful values in C or C++, although your implementation can provide meanings for other values.
I am assuming that you are returning 0 or -1 from the main program as your program exits. What this does is inform the calling program the success or failure of the program. This is not very handy if you just run the program at a command prompt but if your program is called within a script (Perl,PHP, python, PowerShell, etc) you can test to see if the program was successful.
In a nutshell, if your program is called by another program, the calling program can test for success or failure and respond appropriately.
the program is successful and -1 means the program has an error.
Please explain in detail what these statements really mean.
There are situations where a function cannot proceed further, and cannot complete the task that it is specified for it. Such situation is typically called an error. There are many possible sources of errors. One example of that is a function that has pre-conditions for the inputs that were not satisfied by the caller of the function. An example of such pre-condition is square root function that calculates rational numbers (i.e. not complex): There is no result for negative input.
When an error is encountered, it must somehow be communicated to the caller. There are many techniques, but we shall not cover all of them in detail here. I'll mention that one option in C++ is exceptions. Exceptions technique has some useful properties, but it is not universally applicable to all situations.
Another, very simple technique is to return an error code which is an integer value. If we choose 0 to signify no error, the caller of the function can check for error with following pattern:
int error = function(arguments)
if (error) {
// handle error here
}
This pattern is very common in C APIs. C++ inherits C standard library, and it is common to take advantage of C libraries so it is common to encounter this in C++ as well.
Sometimes, a function needs to use the return value for some other purpose. For example, the open call from POSIX standard returns an integer called "file descriptor", which is a positive integer. Since some of the values in the domain of the return type are not used (negative numbers), it can be used to represent error condition as well. Although any negative number is available, -1 was chosen, and this is also quite conventional. In some other APIs different negative numbers represent different errors. Another approach is to store error information elsewhere. The chosen approach in POSIX is to store the error code in a separate variable.
In conclusion: Integer return values are a technique of communicating errors, and 0 is conventionally used to represent success and -1 is often used to represent erroneous execution. The meaning of the return value of a function should be documented by the implementer, and the documentation should be studied carefully by the user of the function.
But what I don't get is why use these statements when the compiler will generate an error if there is one in the program anyway?
It's unclear what you expect here. The compiler cannot read the programmer's mind and know all cases where the program should have an error. It can only tell whether the program is well-formed or not (and maybe give some helpful warnings about obvious mistakes if you're lucky).
It is the programmer's responsibility to consider the error conditions of the program.
The only difference between 0 and -1, as far as the compiler is concerned, is that they are two different numbers. Nothing is assumed whatsoever about their "success" or "failure" status (except in main in which the return value is ignored anyway).
The rest are (mostly bad) conventions used by developers. Usually < 0 for failure and 0 for success and you have created a nice bug when you test against bool (in which -1 is true and 0 is false).
One should use enums or, at least, something more recognizable as in windows HRESULT.
It basically means that anything other then 0 means something bad happened during execution of your program. The program could not deal with it so it exited with the status code.
Often when working with shell you will notice that some of commands exit with non 0 status code. You can check that value by running echo $? command.
And finally you can use return codes to communicate to the client what happend. That is if you describe what return codes can your program return.

How do I return the value after checking for a condition?

The following code has to check for an 'e' value such that the gcd(h,e)=1. Where 1
module great(p,q,e,d);
input p,q;
output e,d;
reg e,d;
h=((p-1)*(q-1));
always
begin
for(e=2;e<h;e=e+1)
begin
g1=gcd(h,e);
if(g1==1)
return e;
If, by "return a value", you mean spit out a value you can use in another module, you would use the output of this module as your "return" value. But even ignoring the return e, I don't think your code will work if you tried to run it, because it is too much like a programming language. There's several major things wrong:
You already declared output e,d so you can't declare two reg with the same name. You probably want output reg e,d instead.
You didn't declare a type for h or g1.
You have a for loop for e but e can never be anything other than 0 or 1 because you didn't set a size for it, so by default it is only 1-bit long. Even if it was big enough that you could increment it past 1, it's a wire type by default, and you can't make those kind of increments to a wire directly.
I assume gcd is some module you made somewhere else, but this isn't how you interconnect modules together. You can't call it like it's a function. You have to use wire and reg to connect the inputs and outputs of two modules together, almost like you're plugging components in.
Those are what stick out the most to me, anyway. I think you are coding your Verilog as if it were Python and that's what's causing these misunderstandings. Verilog is very, very different.

What's the real purpose of `ignore` function in OCaml?

There is an ignore function in OCaml.
val ignore : 'a -> unit
Discard the value of its argument and return (). For instance,
ignore(f x) discards the result of the side-effecting function f. It
is equivalent to f x; (), except that the latter may generate a
compiler warning; writing ignore(f x) instead avoids the warning.
I know what this function will do, but don't get the point of using it.
Anyone can explain or give an example for when we have to use it?
You basically answered your own question. You don't ever have to use it. The point is precisely to avoid the warning. If you write f x; (), the compiler assumes you probably did something wrong. Probably you thought f x returns unit because you rarely want to ignore non-unit values.
However, sometimes that's not true, and you really want to ignore even non-unit values. Writing ignore (f x) documents the fact that you know f x returns something, but you are deliberately ignoring it.
Note that in real code f x might be something more complex, so the chances of you being wrong about the return type of f x are reasonably high. One example is partial application. Consider f : int -> int -> unit. You might accidentally write f 1, forgetting the second argument, and the warning will help you. Another example is if you do open Async, then many functions from the Standard Library change from returning unit to returning unit Deferred.t. Especially when first starting to use Async, it is quite likely that you'll accidentally think the semicolon operator is appropriate in places that you really need to use monadic bind.
As a complement to Ashish Agarwal's answer (because judging from your comment you don't seem very convinced) :
Imagine that I have a function that has side effects, and returns a value indicating something about the computation. Then, if I'm interested in how the computation went, I will need its return value. However, if I don't care about this and simply want the side effects to take place, I would use ignore.
Dumb example : let's say you have a function which sorts an array and returns Was_already_sorted or Was_not_sorted depending on the initial state of the array. Then if for some reason I'm interested in knowing how often my array was sorted, I might need the return value of this function. If not, I will ignore it.
I agree that this is a dumb example. And probably that in many cases there would be better ways to deal with the problem than using ignore (I've just noticed that I never use ignore). If you're really passionate about this, you could try to find examples of use of this function in real-life code (maybe in the source-code of software such as Unison?).
Also, note that you can use let _ = f x to the same end.

Fortran return statement

I'm trying to get some code compiled under gfortran that compiles fine under g77. The problem seems to be from a return statement:
ffuncs.f:934.13:
RETURN E
1
Error: Alternate RETURN statement at (1) requires a SCALAR-INTEGER return specifier
In the code anything E was specified as real*8:
IMPLICIT REAL*8 ( A - H , O -Z )
However, E was never given a value or anything in fact you never see it until the return statement. I know almost nothing about fortran. What is the meaning of a return statement with an argument in fortran?
Thanks.
In FORTRAN (up to Fortran 77, which I'm very familiar with), RETURN n is not used to return a function value; instead, it does something like what in other languages would be handled by an exception: An exit to a code location other than the normal one.
You'd normally call such a SUBROUTINE or FUNCTION with labels as arguments, e.g.
CALL MYSUB(A, B, C, *998, *999)
...
998 STOP 'Error 1'
998 STOP 'Error 2'
and if things go wrong in MYSUB then you do RETURN 1 or RETURN 2 (rather than the normal RETURN) and you'd be hopping straight to label 998 or 999 in the calling routine.
That's why normally you want an integer on that RETURN - it's not a value but an index to which error exit you want to take.
RETURN E sounds wrong to me. Unless there's a syntax I'm unaware of, the previous compiler should have flagged that as an error.
In a Fortran function one returns the value, by assigning the value to a fake variable which is the same name as the function. Once you do that, simply return.
I think #Carl Smotricz has the answer. Does argument list of ffuncs has dummy arguments that are asterisks (to match the asterisk-label in the calls)? Or was this used without there being alternative returns? If there were no alternative returns, just delete the "E". If there are alternative returns, the big question is what the program was doing before at run time since the variable was of the wrong type and uninitialized. If the variable didn't have an integer value matching one of the expected branches, perhaps the program took the regular return branch -- but that's just a guess -- if so, the easy fix is to again to delete the "E".
The "alternate return" feature is considered "obsolescent" by the language standard and could be deleted in a future standard; compilers would likely continue to support it if it were removed because of legacy code. For new code, one simple alternative is to return an integer status variable and use a "select case" statement in the caller.