How to write an empty block - bcpl

How do you write an empty block? For example, in C, you can have { }. But in BCPL, the equivalent $( $) is a syntax error because a block needs at least one statement. So how can you make the following compile?
let foo() be $(
test bar then $(
//to do
$) else $(
writes("baz*n")
$)
$)

Well, for a start, your syntax appears to be off. From memory, the syntax of test is test <expression> then <true-bit> or <false-bit> (though, since there are many variations on BCPL, you could be using one that allows that syntax).
For now, you could just switch to unless to achieve the desired result:
// TODO: refactor later to use "test", and add other case.
unless bar do $(
writes("baz*n")
$)
If you really want to leave it as is, other than possibly fixing the syntax, any null-type statement (one having no effect of the functionality) will do. An example of that could be something like let xyzzy = 42 or writes("").

Related

why strict code format on keywords in go lang

As every new programer starting in Go 1st think you see is, strict code format.
Means:
//Valid
func foo(){
}
//Invalid
func foo()
{
}
Same goes for if-else that else should be in same line where if ends, like:
//Valid
if{
}else{
}
//Invalid
if{
}
else{
}
we get below error:
syntax error: unexpected else, expecting }
I have checked the spec spec, but not able to find why.
The only explanation I'am getting is its mandatory.
Can anyone explain us why this is mandated does this have any reason? if any.
UPDATE
I think i have mention this already that "I know lang say so", Question is WHY?
Why to go this length to make it compile time error, what problems it was posing if we don't do this?
The language was designed as such and the reason is outlined in the FAQ.
https://golang.org/doc/faq
Why are there braces but no semicolons? And why can't I put the opening brace on the next line?
o uses brace brackets for statement
grouping, a syntax familiar to programmers who have worked with any
language in the C family. Semicolons, however, are for parsers, not
for people, and we wanted to eliminate them as much as possible. To
achieve this goal, Go borrows a trick from BCPL: the semicolons that
separate statements are in the formal grammar but are injected
automatically, without lookahead, by the lexer at the end of any line
that could be the end of a statement. This works very well in practice
but has the effect that it forces a brace style. For instance, the
opening brace of a function cannot appear on a line by itself.
Some have argued that the lexer should do lookahead to permit the
brace to live on the next line. We disagree. Since Go code is meant to
be formatted automatically by gofmt, some style must be chosen. That
style may differ from what you've used in C or Java, but Go is a
different language and gofmt's style is as good as any other. More
important—much more important—the advantages of a single,
programmatically mandated format for all Go programs greatly outweigh
any perceived disadvantages of the particular style. Note too that
Go's style means that an interactive implementation of Go can use the
standard syntax one line at a time without special rules.
Go inserts a ; at the end of lines ending in certain tokens including }.
Since if {...} else {...} is a single statement, you can't put a semicolon in the middle of it after the first closing brances i.e. }, hence the requirement to put } else { on one line is mandatory.
I hope it answers your question.

coffeescript chaining with no parameters?

Hi I'm wondering if its possible to omit empty parenthesis when chaining in coffeescript.
for example
myFunction = -> [...]
chain1 = -> [...]
chain2 = -> [...]
myFunction().chain1().chain2()
to instead
myFunction.chain1.chain2
Short answer: no, you can't.
That exact syntax will not work in CoffeeScript. You can only chain methods that have at least one argument, so something like this could work:
myFunction arg1
.chain1 arg2
.chain2 arg3
For jQuery, for example, you can do stuff like:
$ ->
$ '#foo'
.and '.bar'
.click ->
alert 'awesome!'
This is because, unlike in Ruby, where referencing a name without a leading '#' or '::' implies a method or a local variable, in CoffeeScript, myFunction is an expression that returns the function itself. Thus, myFunction.chain1 and myFunction().chain1 can both be valid and mean different things.
Note however, that the new keyword implies a function call, so if myFunction is an (oddly named) constructor, you could write (new myFunction).chain1, but that is again different as .chain1 would be the property of the prototype.
Moreover, if you are the author of the library in question, you could use getters/setters to simulate that behaviour in plain JavaScript, but I would highly discourage that.

Faster alternative to eval?

I'm dealing with a web app that uses a home-grown templating system that lets Perl code be embedded in HTML. These statements are executed by the template parser at run-time using eval EXPR.
This is very flexible, but these statements are scattered everywhere, and get executed a lot. eval EXPR (as opposed to eval BLOCK) requires Perl to fire up the interpreter each time, and my profiling reveals that they're a reasonably significant source of slowdown.
Many of the embedded Perl statements are very simple. For example, a template might have a line like this:
<p>Welcome, <!--E: $user->query('name') -->.
Or:
<p>Ticket number <!--E: $user->generate_ticket_number() --> has been generated.
That is, they're just calling object methods. There are more complicated ones, too, though.
I'm hoping to optimize this, and so far have two ideas, both of which are terrible. The first is to rewrite all templates to replace simple calls with tokens like USER:NAME and USER:GENERATETICKETNUMBER, which the parser could then scan for and invoke the appropriate object method. But then instead of dealing with templates that mix HTML and Perl, I would have templates that mix HTML, Perl, and tokens.
The second idea is to try to parse the embedded Perl, figure out what the statement wants to do, and, if it's simple enough, call the appropriate object method via a symbolic reference. This is obviously insane.
Is there some logical solution I'm overlooking?
Try taking an approach similar to the one that mod_perl uses to compile CGIs:
Convert the template into Perl code. For instance, your first example might convert to something like:
print "<p>Welcome, ";
print $user->query('name');
print ".\n";
Wrap a sub { ... } around that code, along with some code to unpack arguments (e.g, for things like $user in the sample).
eval that code. Note that it returns a coderef.
Call that coderef repeatedly. :)
You might take a look at Mojolicious. It has a templating engine which allow a syntax close to what you are using. You could possibly switch to use it or look at its source (click source on left of previous link) to see if you can draw some ideas.
FYI the Mojolcious templating engine's syntax allows the following forms intermixed with HTML appropriately
<% Perl code %>
<%= Perl expression, replaced with result %>
<%== Perl expression, replaced with XML escaped result %>
<%# Comment, useful for debugging %>
<%% Replaced with "<%", useful for generating templates %>
% Perl code line, treated as "<% line =%>"
%= Perl expression line, treated as "<%= line %>"
%== Perl expression line, treated as "<%== line %>"
%# Comment line, treated as "<%# line =%>"
%% Replaced with "%", useful for generating templates
You might want to look at the guts of Text::MicroTemplate. Realistically, you might want to use Text::MicroTemplate, as it likely fits your needs. It builds a subroutine that concatenates strings as needed, much like duskwuff suggested. Here's the result of build_mt('hello, <?= $_[0] ?>') in re.pl:
$CODE1 = sub {
package Devel::REPL::Plugin::Packages::DefaultScratchpad;
use warnings;
use strict 'refs';
local $SIG{'__WARN__'} = sub {
print STDERR $_mt->_error(shift(), 4, $_from);
}
;
Text::MicroTemplate::encoded_string(sub {
my $_mt = '';
local $_MTREF = \$_mt;
my $_from = '';
$_mt .= 'hello, ';
$_from = $_[0];
$_mt .= ref $_from eq 'Text::MicroTemplate::EncodedString' ? $$_from : do {
$_from =~ s/([&><"'])/$Text::MicroTemplate::_escape_table{$1};/eg;
$_from
};
return $_mt;
}
->(#_));
};
You should not be using 'eval' to call methods in your template. Sorry to sound harsh but the point of a separated view is to remove the processing code from the view layer. The template systems described above along with Template Toolkit just pass in an object / hash so you can access it.
why not pass $user as a hashref like:
$user = {
'name' => 'John',
'id' => '3454'
};
this will allow you to access 'name' with:
$user->{'name'};
Otherwise, it's likely that you have that you're doing something like:
template calls $user->query();
method calls DB to get value
method returns value
That's soooo much more expensive to make a database query than to pass the hash/object reference to the template. You may want to check out some code profiling tools like Devel::NYTProf to see what part of the code execution is really slowing you down. I'm skeptical that the eval is bogging down your program so much that you need to optimize out eval. Sounds like the code inside eval is what is slowing you down.

Emacs ruby-mode, indenting wildly inside parentheses?

Excuse my emacs newbiness here, but does anybody know how to get around this? When coding in emacs, in ruby-mode, it indents to the correct level (i.e. by 2 spaces) after all the keywords, like def, class, module, begin etc, but when breaking parameter lists across multiple lines, it indents to a seemingly random position, like 40 or so columns over.
I've been reading around emacs tab settings and seem to just be going around in circles and not getting to information I'm looking for, so I figured I'd ask here.
Here's a screenshot of where it is placing the cursor in a parameter list. I've tried indenting inside of curly braces (e.g. for a block, or a hash) and that is working ok, it's the parentheses that are messing it up.
http://compgroups.net/comp.emacs/Ruby-mode-indentation-of-continuation-lines
(setq ruby-deep-indent-paren nil)
Or temporarily, within the current session:
M-x set-variable RET ruby-deep-indent-paren RET nil RET
Inside of a parentheses it will now indent like it does everywhere else. There is still a minor bug in the case of what I posted above. It indents 2 spaces further than I want it to, because I'm confusing it with the combination of ( and {.
ruby-deep-indent-paren and related vars have no effect for me because ruby-use-smie is t. Setting both to nil didn't seem to help either :-(
But switching to enh-ruby-mode, it's working!
Setting enh-ruby-deep-indent-paren to nil had an effect.
Setting enh-ruby-bounce-deep-indent to t allows me to press Tab again to toggle between the styles!
Basically it's trying to line up the args in a multi-line list of parenthesized arguments, like:
function_call (arg1,
arg2);
Setting the ruby-deep-indent-paren to nil as above changes the behvaior to the annoying double-indenting for mixed braces, e.g.:
if (cond) then
do_stuff
end
function_call (&proc {
do_stuff
})
The indenting wierdness is really bothering me. I edited Mats' original ruby-mode.el code to try and indent more sanely. But I can't get it cleaned up for the life of me.

ruby idiom: predicates and the conditional operator

I like judicious use of the ternary, conditional operator. To my mind it's quite succinct.
However, in ruby, I find I'm often testing predicate methods, which already have their own question marks:
some_method( x.predicate? ? foo : bar )
I'm jarred by those two question marks so close to each other. Is there an equivalently compact and readable alternative?
The reason why the conditional operator is needed in C, is because the conditional statement is, well, a statement, i.e. it doesn't (and cannot) return a value. So, if you want to return a value from conditional code, you're out of luck. That's why the conditional operator had to be added: it is an expression, i.e. it returns a value.
In Ruby, however, the conditional operator is completely superfluous because there are no statements is Ruby anyway. Everything is an expression. Specifically, there is no if statement in Ruby, there is only an if expression.
And since if is an expression anyway, you can just use it instead of the cryptic conditional operator:
some_method( if x.predicate? then foo else bar end )
The only thing you have to remember is that the predicate needs to be terminated by either a newline, a semicolon or a then. So, the first three times you do this, you will turn
if cond
foo
else
bar
end
into
if cond foo else bar end
and wonder why it doesn't work. But after that, the then (or semicolon) will come naturally:
if cond; foo else bar end
if cond then foo else bar end
The closest succinct expression you can get is
x.predicate? && foo || bar
which acts sort of a ternary operator, but more cryptic and ugly.
It's just a case of syntactic diabetes caused by the sugar on the query? methods. I guess we'll just have to learn to live with it.
Just remove the space.
some_method( x.predicate?? foo : bar )
Is equally valid in Ruby. Try it!
Can't say it's easier, but in many cases it might be useful just to wrap predicate itself into brackets, like this:
some_method((x.predicate?) ? foo : bar )
It helps, especially when your predicate is not as simple as method?

Resources