Raku last on non-loops - block

I have something that I can do easily in Perl, but not in Raku without fiddling around with flag variables. Here's the Perl code:
#!/usr/bin/perl
MAIN_BLOCK: {
foreach $item (1 2 3 4 5) {
$item == 6 and last MAIN_BLOCK;
}
print "No items matched!\n";
}
The relevant difference here is that Perl will allow you to use last to exit from any labelled block. Raku will only do this if the block is a loop.
Is there a good way to do this? I feel like there should be a phaser for this, but haven't figured out how to do it without flag variables, which seem like they should be avoidable.
Thanks,

Raku supports similar control flow with given blocks.
Here's a fairly literal translation (i.e., not necessarily idiomatic Raku) from the Perl code you posted:
given * {
for ^6 -> $item {
succeed if $item == 6;
}
default { print "No items matched!\n"; }
}
edit: Oh, and for a less-literally-translated/more-idiomatic-Raku solution, well, TIMTOWTDI but I might go with returning from an anonymous sub:
sub { for ^6 { return when 6 }
say "No items matched!" }()
(Of course, I suppose it's possible that the most Raku-ish way to solve do that doesn't involve any Raku syntax at all – but instead involves modifying one of Raku's braided languages to allow for loops to take an else block. But I'm not advising those sort of shenanigans!)

Related

refactor if to takeIf and return "return" without label kotlin

I am trying to write more idiomatic Kotlin code and I am stuck with the best way to refactor this if condition. Basically when the condition if true (fragment is GenericActionsBottomSheetDialog instance in a list of Fragments) I return the funcion itself.
Here is what I had and how I refactored it. Is there better way to achieve it? After my refactoring it get worse:
Before refactor:
supportFragmentManager.fragments.iterator().forEach {
if (it is GenericActionsBottomSheetDialog)
return
After refactor:
supportFragmentManager.fragments.iterator().forEach { it ->
it.apply {
takeIf { it is GenericActionsBottomSheetDialog }?.apply { return }}}
If this forEach is the only thing in your current function (which it should IMO), you could get rid of the non-local return by using takeWhile instead:
supportFragmentManager.fragments
.takeWhile { it !is GenericActionsBottomSheetDialog }
.forEach {
// do stuff
}
/!\ be careful that this changes semantics if there is other stuff after the forEach in the same function declared with fun.
If you expect many fragments in the list, you could also use asSequence() before takeWhile so you don't create an intermediate list.
Here's one possibility, which separates the decision from the action:
if (supportFragmentManager.fragments.any{ it is GenericActionsBottomSheetDialog })
return
I think this approach makes the intent clearest. (It's also about the most efficient.)
any() simply checks each item in turn, stopping when it finds a match (or when it reaches the end of the list). Kotlin has many functions like this (inspired by functional programming languages) that use lambdas to operate on lists and other structures. They tend to be named for what they do, rather than how they do it — which makes code using them both short and easy to read. (You should be writing code for people to read, as much as for computers to execute!)
For completeness, here's another approach, which uses filterIsInstance():
if (supportFragmentManager.fragments
.filterIsInstance<GenericActionsBottomSheetDialog>)
.isNotEmpty())
return
There are bound to be many other ways. But I agree with the commenter that your ‘refactored’ approach, while using many more Kotlin functions, has little else to recommend it!
This is an opinion based question, and answers cannot be any different.
That being said: there is nothing wrong with if clauses. From what I can see from your current question, I'd leave it with an if.
Now, if you really do not want to use it, filter elements that are not of type GenericActionsBottomSheetDialog and apply whatever function you want on them (the part that is in your else clause, which we do not see).
EDIT:
In case you only want to check if the object of the GenericActionsBottomSheetDialog exists in the collection, you can perhaps do it like this:
val dialogExists = supportFragmentManager.fragments
.firstOrNull { it is GenericActionsBottomSheetDialog} != null
if (dialogExists) {
return
}
#gidds solution is IMO the most idiomatic one:
if (supportFragmentManager.fragments
.any { it is GenericActionsBottomSheetDialog }) return
I would like to add this solution eliminating the if:
supportFragmentManager.fragments
.firstOrNull { it is GenericActionsBottomSheetDialog }
?.run { return }
It's a matter of taste which one you pick, I prefer the first one.
I was wondering why you use the iterator? You could simply do:
supportFragmentManager.fragments.forEach {

Can I write multiple raku Type smart matches on one line

I know that this will not work, since I tried it:
if $r ~~ BearingTrue || CompassAdj || CourseAdj { nextsame };
But - is there a neat, concise and legible way to do multiple Type smart matches on one line rather than have to expand to a given/when or if/else construct?
Have you tried :
if $r ~~ BearingTrue | CompassAdj | CourseAdj { nextsame };
This should give you an Any Junction that with then match OK.
This Answer is to let me address the comment from #jubilatious1 a bit more clearly.
I am working on a new raku module, see line 225 ish here Physics::Navigation
For illustrative purposes, the code now looks like this...
class BearingTrue { ...}
class BearingMag { ...}
sub err-msg { die "Can't mix BearingTrue and BearingMag for add/subtract!" }
class BearingTrue is Bearing is export {
multi method compass { <T> } #get compass
multi method compass( Str $_ ) { #set compass
die "BearingTrue compass must be <T>" unless $_ eq <T> }
method M { #coerce to BearingMag
my $nv = $.value + ( +$variation + +$deviation );
BearingMag.new( value => $nv, compass => <M> )
}
#| can't mix unless BearingMag
multi method add( BearingMag ) { err-msg }
multi method subtract( BearingMag ) { err-msg }
}
So I decided to recast the code to use multi-method add and subtract to check type matches to prevent a lost mariner from adding a magnetic bearing to a true one. I feel that this is cleaner even than Scimon's great answer, since in that instance, my method was accepting all child types of Bearing and then using an if statement to detect a type error.
You are welcome to go...
zef install https://github.com/p6steve/raku-Physics-Navigation.git
then follow the example at the top of bin/synopsis-navigation.raku to use the module and make the various classes available in your own code.
If you are just keen to see how the pieces fit then I suggest writing your own simple classes on similar lines and working through the examples in books such as ThinkRaku chapter 12. I recommend this for the clarity and level of information and it treats inheritance and roles equally.
I am confident that others will feel my code style is over-reliant on inheritance. I feel that since a magnetic-bearing is strictly a derived concept from a bearing-in-general that this is right for my code - but roles and composition is less restrictive and provides similar encapsulation with better maintainability.

Bypassing functions that do not exist

how would it be possible to bypass functions that are not existing in DM
such that the main code would still run? Try/catch does not seem to work, e..g
image doSomething(number a,number b)
{
try
{
whateverfunction(a,b)
}
catch
{
continue
}
}
number a,b
doSomething(a,b)
Also conditioning wont work, e.g..
image doSomething(number a,number b)
{
if(doesfunctionexist("whateverfunction"))
{
whateverfunction(a,b)
}
}
number a,b
doSomething(a,b)
thanks in advance!
As "unknown" commands are caught by the script-interpreter, there is no easy way to do this. However, you can construct a workaround by using ExecuteScriptCommand().
There is an example tutorial to be found in this e-book, but in short, you want to do something like the following:
String scriptCallStr = "beep();\n"
scriptCallStr = "MyUnsaveFunctionCall();\n"
number exitVal
Try { exitVal = ExecuteScriptString(scriptCallStr ); }
Catch { exitVal = -1; break; }
if ( -1 == exitVal )
{
OKDialog("Sorry, couldn't do:\n" + scriptCallStr )
}
else
{
OKDialog( "All worked. Exit value: " + exitVal )
}
This works nicely and easy for simple commands and if your task is only to "verify" that a script could run.
It becomes clumsy, when you need to pass around parameters. But even then there are ways to do so. (The 'outer' script could create an object and pass the object-ID per string. Similarly, the 'inner' script can do the same and return the script-object ID as exit-value.)
Note: You can of course also put doesfunctionexist inside the test-script, if you do only want to have a "safe test", but don't actually want to execute the command.
Depending on what you need there might also be another workaround solution: Wrapper-functions in a library. This can be useful if you want to run the same script on different PCs with some of which having the functionality - most likely some microscope - while others don't.
You can make your main-script use wrapper methods and then you install different versions of the wrapper method script scripts as libraries.
void My_SpecialFunction( )
{
SpecialFunction() // use this line on PCs which have the SpecialFunction()
DoNothing() // use alternative line on PCs which don't have the SpecialFunction()
}
My_SpecialFunction( )
I have used this in the past where the same functionality (-stage movement-) required different commands on different machines.

Why can't I call "gist" on "while"? (Perl 6)

I can call the gist method on the say built-in function:
&say.gist
sub say (| is raw) { #`(Sub|54790064) ... }
Why can't I call gist on while?
&while.gist
===SORRY!=== Error while compiling <unknown file>
Undeclared routine:
while used at line 1
Obviously while isn't a "routine" but say is. But I thought that all of the built-ins in Perl 6 were really functions that we could redefine.
I thought that all of the built-ins in Perl 6 were really functions that we could redefine.
while is not a routine or macro, but part of the syntax, defined in Perl6's grammar.
If you wanted to redefine it, you would have to create your own slang, which currently involves black magic.
For some reason I have yet to figure out, it only works when done in a module (otherwise, %*LANG seems not to be defined).
Let's call the module froop.pm6:
use nqp;
sub EXPORT {
nqp::bindkey(%*LANG, 'MAIN', nqp::atkey(%*LANG, 'MAIN').^mixin(role {
rule statement_control:sym<while> {
[$<sym>=froop{
$/.hash<sym>.^mixin: role {
method Str { 'while' }
}
}|$<sym>=until]<.kok> {}
<xblock>
}
}));
once Map.new
}
This replaces the while keyword (in statement position) with froop, eg
use froop;
my $i = 0;
froop $i < 5 { say $i++ }

How do I exit a Rust program early from outside the main function?

I am in the process of writing a bash clone in Rust. I need to have my program exit when the user types exit. In previous iterations of my program, before I added more complicated features, I used return to get out of the loop that was prompting the user for input. This logic is now in a function, because of the way I am implementing built in shell functions, so when I return it just jumps out of the function back into the control loop, instead of short-circuiting the control loop and ending the program.
I realize that I could probably return a boolean when the user types exit and exit the loop, but I would like to at least know if Rust has a way to terminate programs early, similar to Java's System.exit(), as this is useful for certain types of programs.
Rust 1.0 stable
std::process::exit() does exactly that - it terminates the program with the specified exit code:
use std::process;
fn main() {
for i in 0..10 {
if i == 5 {
process::exit(1);
}
println!("{}", i);
}
}
This function causes the program to terminate immediately, without unwinding and running destructors, so it should be used sparingly.
Alternative (not recommended) solution
You can use C API directly. Add libc = "0.2" to Cargo.toml, and:
fn main() {
for i in 0..10 {
if i == 5 {
unsafe { libc::exit(1); }
}
println!("{}", i);
}
}
Calling C functions cannot be verified by the Rust compiler, so this requires the unsafe block. Resources used by the program will not be freed properly. This may cause problems such as hanging sockets.
As far as I understand, the proper way to exit from the program is to terminate all threads somehow, then the process will exit automatically.
panic!("Oh no something bad has happened!")
Example:
if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); }
In older documentation, you will see this as fail!("Oh no something bad here has happened.")
For some reason, this macro was changed from fail to panic. Panic is the way to fail, if you must.
[edit] I am sorry. It looks like you should be testing input for the string "exit," which would depend on how you are taking input (by line or by args). Then you can have the program break out of the loop on the condition that the exit is detected.
Example:
loop {
if exit_found { break }
else {
// your thing, which also looks for exit_found
}
}