What is good style for variable declaration in fortran? - coding-style

So I have a whole lot of variables I need to declare, and the original code looked like this:
DIMENSION energy_t(20000),nrt(20000),npsh(1000),xx(1000),yy(1000),
:step(1000),stepz(1000),r1(1000),rr(1000),ic(1000),diffrr(1000)
And I rewrote it as this:
DIMENSION
:energy_t(20000),
:nrt(20000),
:npsh(1000),
:step(1000),
:r1(1000),
:rr(1000),
:ic(1000),
:diffrr(1000)
Is this considered good style, or are there better ways? Note that the second way allows for comments with each variable, and I don't have to use line continuations if I might add another variable.
P.S.: is there a consensus/style bible/widely regarded source on Fortran programming style & good practices?

Good style is not to use the dimension statement in the first place. Especially if you use implicit typing. Every variable should have a declared type and is better to put the array dimension there. Use attributes with the type declaration (Fortran 90+).
real :: energy_t(20000), nrt(20000)
real, dimension(1000) :: npsh, xx, yy, step, stepz, r1, rr, ic, diffrr
Keep lines not too long. Both ways of declaring size (shape) are possible.
If you need Fortran 77, you are more limited, but still
real energy_t(20000), nrt(20000)
real npsh(1000), xx(1000), yy(1000), step(1000), stepz(1000)
real r1(1000), rr(1000), ic(1000), diffrr(1000)
is probably better.
Try to group related variables on one line and the others on different lines.
I would also suggest to declare parameter constants for the sizes 1000 and 20000.

Good style would be to parametrize the dimensions
integer, parameter:: NODES_MAX = 1000, TIMES_MAX = 2000, COORD_MAX = 1000
real energy_t(TIMES_MAX), ..
real npsh(NODES_MAX), xx(COORD_MAX) ...
so that the loops can be parameterized.
do ii = 1, COORD_MAX
xx(ii) = ...
yy(ii) = ..
end do
and error checks can be made
if (ii .gt. NODES_MAX) then
print *, 'Please increase NODES_MAX oldvalue=', NODES_MAX, ' required=', ii
pause
end if
This will also minimize the number of changes required when the dimensions are increased/decreased. This style could also have been applied 30+ years ago when F77 came out.

Related

Halide::Expr' is not contextually convertible to 'bool' -- Storing values of functions in variables

I am new to using Halide and I am playing around with implementing algorithms first. I am trying to write a function which, depending on the value of the 8 pixels around it, either skips to the next pixel or does some processing and then moves on to the next pixel. When trying to write this I get the following compiler error:
84:5: error: value of type 'Halide::Expr' is not contextually convertible to 'bool'
if(input(x,y) > 0)
I have done all the tutorials and have seen that the select function is an option, but is there a way to either compare the values of a function or store them somewhere?
I also may be thinking about this problem wrong or might not be implementing it with the right "Halide mindset", so any suggestions would be great. Thank you in advance for everything!
The underlying issue here is that, although they are syntactically interleaved, and Halide code is constructed by running C++ code, Halide code is not C++ code and vice versa. Halide code is entirely defined by the Halide::* data structures you build up inside Funcs. if is a C control flow construct; you can use it to conditionally build different Halide programs, but you can't use it inside the logic of the Halide program (inside an Expr/Func). select is to Halide (an Expr which conditionally evaluates to one of two values) as if/else is to C (a statement which conditionally executes one of two sub-statements).
Rest assured, you're hardly alone in having this confusion early on. I want to write a tutorial specifically addressing how to think about staged programming inside Halide.
Until then, the short, "how do I do what I want" answer is as you suspected and as Khouri pointed out: use a select.
Since you've provided no code other than the one line, I'm assuming input is a Func and both x and y are Vars. If so, the result of input(x,y) is an Expr that you cannot evaluate with an if, as the error message indicates.
For the scenario that you describe, you might have something like this:
Var x, y;
Func input; input(x,y) = ...;
Func output; output(x,y) = select
// examine surrounding values
( input(x-1,y-1) > 0
&& input(x+0,y-1) > 0
&& ...
&& input(x+1,y+1) > 0
// true case
, ( input(x-1,y-1)
+ input(x+0,y-1)
+ ...
+ input(x+1,y+1)
) / 8
// false case
, input(x,y)
);
Working in Halide definitely requires a different mindset. You have to think in a more mathematical form. That is, a statement of a(x,y) = b(x,y) will be enforced for all cases of x and y.
Algorithm and scheduling should be separate, although the algorithm may need to be tweaked to allow for better scheduling.

Mathematica - can I define a block of code using a single variable?

It has been a while since I've used Mathematica, and I looked all throughout the help menu. I think one problem I'm having is that I do not know what exactly to look up. I have a block of code, with things like appending lists and doing basic math, that I want to define as a single variable.
My goal is to loop through a sequence and when needed I wanted to call a block of code that I will be using several times throughout the loop. I am guessing I should just put it all in a loop anyway, but I would like to be able to define it all as one function.
It seems like this should be an easy and straightforward procedure. Am I missing something simple?
This is the basic format for a function definition in Mathematica.
myFunc[par1_,par2_]:=Module[{localVar1,localVar2},
statement1; statement2; returnStatement ]
Your question is not entirely clear, but I interpret that you want something like this:
facRand[] :=
({b, x} = Last#FactorInteger[RandomInteger[1*^12]]; Print[b])
Now every time facRand[] is called a new random integer is factored, global variables b and x are assigned, and the value of b is printed. This could also be done with Function:
Clear[facRand]
facRand =
({b, x} = Last#FactorInteger[RandomInteger[1*^12]]; Print[b]) &
This is also called with facRand[]. This form is standard, and allows addressing or passing the symbol facRand without triggering evaluation.

vb6 & character after a variable [duplicate]

This question already has answers here:
What do ! and # mean when attached to numbers in VB6?
(3 answers)
Closed 9 years ago.
There is the following in some code I'm trying to figure out:
For I& = 1 To...
I'm not familiar with the & after a variable. What does that represent?
After some further research, it looks like the I& is being defined as a type LONG. Now my questions is why would they be doing this? Is it overkill or just legacy code?
The legacy BASIC Language had several ways of declaring variables. You could use data type suffixes ($, %, &, !, or #) to the variable name
x$ = "This is a string" ' $ defines a string
y% = 10 ' % defines an integer
y& = 150 ' & defines a long integer
y! = 3.14 ' ! defines a single
y# = 12.24 ' # defines a double
Legacy. Old-school (pre-.NET) Visual Basic used variable name suffixes in lieu of (optionally) variable types.
You are right - putting an ampersand & after a number or a variable means that it is of a Long 32-bits type.
So the answer is, how many iterations does the loop need - is it possible, that it would exceed 16 bits integer?
With no data type identifier after the i, it is implied to be of the native Integer (the default). Therefore this i is expressed as an Integer, which makes it a 16-bit i.
So, I'd say it is the original developer had this habit of explicitly stating the variable type with &, and whether it was really needed there depends on the number of iterations that the For..Next loop has to support in this case.
Most likely it is either old code ported forward to VB6 from QBasic, etc. or else just a bad habit some individual programmer had from that era. While kind of sloppy its meaning should be obvious to a VB6 programmer, since it can be used with numeric literals in many cases too:
MsgBox &HFFFF
MsgBox &HFFFF&
These display different values because they are different values.
Yes it means Long but it often reflects somebody who fails to set the IDE option to auto-include Option Explicit in new modules when created.
Using symbolic notation (Integer - %, Long - &, Single - !, Double - #, String - $) is an excellent method for variable declaration and usage. It’s usage is consistent with "structured programming" and it’s a good alternative to Hungarian notation.
With Hungarian notation, one might define a string filename as “strFileName”, where the variable name is preceded by a lower case abbreviation of the variable type. The is contrary to another good programming practice of making all global variables begin with an upper case first letter and all local variables begin with a lower case. This helps the reader of your code instantly know the scope of a variable. Ie. firstName$ is a local string variable; LastName$ is a global string variable.
As with all programming, it’s good to follow conventions, ..whether you define your own conventions or somebody else’s conventions or industry conventions. Following no conventions is a very poor programming practice. Using symbolic notation is one type of naming convention.

What are the pros and cons of putting as much logic as possible in a minimum(one-liners) piece of code?

Is it cool?
IMO one-liners reduces the readability and makes debugging/understanding more difficult.
Maximize understandability of the code.
Sometimes that means putting (simple, easily understood) expressions on one line in order to get more code in a given amount of screen real-estate (i.e. the source code editor).
Other times that means taking small steps to make it obvious what the code means.
One-liners should be a side-effect, not a goal (nor something to be avoided).
If there is a simple way of expressing something in a single line of code, that's great. If it's just a case of stuffing in lots of expressions into a single line, that's not so good.
To explain what I mean - LINQ allows you to express quite complicated transformations in relative simplicity. That's great - but I wouldn't try to fit a huge LINQ expression onto a single line. For instance:
var query = from person in employees
where person.Salary > 10000m
orderby person.Name
select new { person.Name, person.Deparment };
is more readable than:
var query = from person in employees where person.Salary > 10000m orderby person.Name select new { person.Name, person.Deparment };
It's also more readabe than doing all the filtering, ordering and projection manually. It's a nice sweet-spot.
Trying to be "clever" is rarely a good idea - but if you can express something simply and concisely, that's good.
One-liners, when used properly, transmit your intent clearly and make the structure of your code easier to grasp.
A python example is list comprehensions:
new_lst = [i for i in lst if some_condition]
instead of:
new_lst = []
for i in lst:
if some_condition:
new_lst.append(i)
This is a commonly used idiom that makes your code much more readable and compact. So, the best of both worlds can be achieved in certain cases.
This is by definition subjective, and due to the vagueness of the question, you'll likely get answers all over the map. Are you referring to a single physical line or logical line? EG, are you talking about:
int x = BigHonkinClassName.GetInstance().MyObjectProperty.PropertyX.IntValue.This.That.TheOther;
or
int x = BigHonkinClassName.GetInstance().
MyObjectProperty.PropertyX.IntValue.
This.That.TheOther;
One-liners, to me, are a matter of "what feels right." In the case above, I'd probably break that into both physical and logic lines, getting the instance of BigHonkinClassName, then pulling the full path to .TheOther. But that's just me. Other people will disagree. (And there's room for that. Like I said, subjective.)
Regarding readability, bear in mind that, for many languages, even "one-liners" can be broken out into multiple lines. If you have a long set of conditions for the conditional ternary operator (? :), for example, it might behoove you to break it into multiple physical lines for readability:
int x = (/* some long condition */) ?
/* some long method/property name returning an int */ :
/* some long method/property name returning an int */ ;
At the end of the day, the answer is always: "It depends." Some frameworks (such as many DAL generators, EG SubSonic) almost require obscenely long one-liners to get any real work done. Othertimes, breaking that into multiple lines is quite preferable.
Given concrete examples, the community can provide better, more practical advice.
In general, I definitely don't think you should ever "squeeze" a bunch of code onto a single physical line. That doesn't just hurt legibility, it smacks of someone who has outright disdain for the maintenance programmer. As I used to teach my students: always code for the maintenance programmer, because it will often be you.
:)
Oneliners can be useful in some situations
int value = bool ? 1 : 0;
But for the most part they make the code harder to follow. I think you only should put things on one line when it is easy to follow, the intent is clear, and it won't affect debugging.
One-liners should be treated on a case-by-case basis. Sometimes it can really hurt readability and a more verbose (read: easy-to-follow) version should be used.
There are times, however when a one-liner seems more natural. Take the following:
int Total = (Something ? 1 : 2)
+ (SomethingElse ? (AnotherThing ? x : y) : z);
Or the equivalent (slightly less readable?):
int Total = Something ? 1 : 2;
Total += SomethingElse ? (AnotherThing ? x : y) : z;
IMHO, I would prefer either of the above to the following:
int Total;
if (Something)
Total = 1;
else
Total = 2;
if (SomethingElse)
if (AnotherThing)
Total += x;
else
Total += y;
else
Total += z
With the nested if-statements, I have a harder time figuring out the final result without tracing through it. The one-liner feels more like the math formula it was intended to be, and consequently easier to follow.
As far as the cool factor, there is a certain feeling of accomplishment / show-off factor in "Look Ma, I wrote a whole program in one line!". But I wouldn't use it in any context other than playing around; I certainly wouldn't want to have to go back and debug it!
Ultimately, with real (production) projects, whatever makes it easiest to understand is best. Because there will come a time that you or someone else will be looking at the code again. What they say is true: time is precious.
That's true in most cases, but in some cases where one-liners are common idioms, then it's acceptable. ? : might be an example. Closure might be another one.
No, it is annoying.
One liners can be more readable and they can be less readable. You'll have to judge from case to case.
And, of course, on the prompt one-liners rule.
VASTLY more important is developing and sticking to a consistent style.
You'll find bugs MUCH faster, be better able to share code with others, and even code faster if you merely develop and stick to a pattern.
One aspect of this is to make a decision on one-liners. Here's one example from my shop (I run a small coding department) - how we handle IFs:
Ifs shall never be all on one line if they overflow the visible line length, including any indentation.
Thou shalt never have else clauses on the same line as the if even if it comports with the line-length rule.
Develop your own style and STICK WITH IT (or, refactor all code in the same project if you change style).
.
The main drawback of "one liners" in my opinion is that it makes it hard to break on the code and debug. For example, pretend you have the following code:
a().b().c(d() + e())
If this isn't working, its hard to inspect the intermediate values. However, it's trivial to break with gdb (or whatever other tool you may be using) in the following, and check each individual variable and see precisely what is failing:
A = a();
B = A.b();
D = d();
E = e(); // here i can query A B D and E
B.C(d + e);
One rule of thumb is if you can express the concept of the one line in plain language in a very short sentence. "If it's true, set it to this, otherwise set it to that"
For a code construct where the ultimate objective of the entire structure is to decide what value to set a single variable, With appropriate formatting, it is almost always clearer to put multiple conditonals into a single statement. With multiple nested if end if elses, the overall objective, to set the variable...
" variableName = "
must be repeated in every nested clause, and the eye must read all of them to see this.. with a singlr statement, it is much clearer, and with the appropriate formatting, the complexity is more easily managed as well...
decimal cost =
usePriority? PriorityRate * weight:
useAirFreight? AirRate * weight:
crossMultRegions? MultRegionRate:
SingleRegionRate;
The prose is an easily understood one liner that works.
The cons is the concatenation of obfuscated gibberish on one line.
Generally, I'd call it a bad idea (although I do it myself on occasion) -- it strikes me as something that's done more to impress on how clever someone is than it is to make good code. "Clever tricks" of that sort are generally very bad.
That said, I personally aim to have one "idea" per line of code; if this burst of logic is easily encapsulated in a single thought, then go ahead. If you have to stop and puzzle it out a bit, best to break it up.

Marking-up argument names in comments of functions

One of the most common dilemmas I have when commenting code is how to mark-up argument names. I'll explain what I mean:
def foo(vector, widht, n=0):
""" Transmogrify vector to fit into width. No more than n
elements will be transmogrified at a time
"""
Now, my problem with this is that the argument names vector, width and n are not distinguished in that comment in any way, and can be confused for simple text. Some other options:
Transmogrify 'vector' to fit into
'width'. No more than 'n'
Or maybe:
Transmogrify -vector- to fit into
-width-. No more than -n-
Or even:
Transmogrify :vector: to fit into
:width:. No more than :n:
You get the point. Some tools like Doxygen impose this, but what if I don't use a tool ? Is this language dependent ?
What do you prefer to use ?
I personally prefer single quotes--your first example. It seems closest to how certain titles / named entities can be referenced in English text when neither underlining nor italics are available.
I agree with Reuben: The first example is the most readable.
Of course that depends on your personal reading habits - If you got used to read comments in the style of your third example, you may find that style the most readable.
But the first style is closest to the way we read and write text in day-to-day life (newspapers, book). Therefore it is the one that will be easiest to read for someone who has no prior experience to reading your comments.
In kinda use neither, and simply put the names of the variables in the text. Or I write the whole text in such a way that it explains what the function does, but does not mention the parameters in it. That's in the case when the meaning of the parameters should become clear by itself when you understand what the function does.
My favourite option is to write:
def foo(vector, width, n=0):
""" Transmogrify 'vector' to fit into 'width'. No more than 'n'
elements will be transmogrified at a time
#param vector: list of something
#param width: int
#keyword n: int (default 0)
"""
Epydoc recognizes #param (see Epydoc manual), and you can use some fancy regexp to find and print parameters of your function, and hopefully Eclipse will start to show parameters description for Python functions in quick assist some day, and I'm pretty sure that it would follow pattern
# <keyword> <paramName> <colon>
Anyway, when that day come it will be easy to replace #param with #anythingElse.

Resources