Is there any way to get around including an unreachable return statement in go? - return

I have the following function:
func fitrange(a, x, b int) int {
if a > b {
a, b = b, a
}
switch true {
case x < a:
return a
case x > b:
return b
default:
return x
}
}
The go compiler complains that the "function ends without a return statement" even though every possible path through the switch statement returns a value. Is there any way to get around this other than adding a dummy return statement at the end of the function?

Remove the default case all together and return x after the switch.
Like:
func fitrange(a, x, b int) int {
if a > b {
a, b = b, a
}
switch true {
case x < a:
return a
case x > b:
return b
}
return x
}

Instead of adding a return at the end, you can also pacify the compiler by adding a panic. It's not a bad idea because if your code contains a bug and that "unreachable" line is ever reached, your program will halt promptly rather than plow ahead with a potentially wrong answer.

Related

Trailing closure issue in swift?

Hello i have a created a function which accepts last argument as closure.
func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
Now i when i call this function.One way to call this function is below like this .
sum(from: 1, to: 10) { (num) -> (Int) in
return 10
}
I have seen one of the concepts in swift as trailing closure.With trailing closure i can call the function like this .
sum(from: 1, to: 10) {
$0
}
but i don't know why it is able to call without any return statement.please tell me how it is happening ?
There really is no answer here except "because the language allows it." If you have a single expression in a closure, you may omit the return.
The section covering this is "Implicit Returns from Single-Expression Closures" from The Swift Programming Language.
Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration, as in this version of the previous example:
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Here, the function type of the sorted(by:) method’s argument makes it clear that a Bool value must be returned by the closure. Because the closure’s body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted.
This has nothing to do with trailing closure syntax, however. All closures have implicit returns if they are single-expression.
As #rob-napier states, you can do it just because the language allows it.
But, note your example is also doing two different things in that last part:
sum(from: 1, to: 10) {
$0
}
Not only are you omitting the return statement, you're also omitting the named parameters, so the $0 is not dependant on the omitting the return feature.
This would be a more accurate example for just omitting return:
sum(from: 1, to: 10) { (num) -> (Int) in
num
}
That said, I wouldn't recommend using either of these features. In most cases, it's better to make the code easier to read later. Your future self (and others who use the code after you) will thank you.

Why does the closure for `take_while` take its argument by reference?

Here is an example from Rust by Example:
fn is_odd(n: u32) -> bool {
n % 2 == 1
}
fn main() {
println!("Find the sum of all the squared odd numbers under 1000");
let upper = 1000;
// Functional approach
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n) // All natural numbers squared
.take_while(|&n| n < upper) // Below upper limit
.filter(|n| is_odd(*n)) // That are odd
.fold(0, |sum, i| sum + i); // Sum them
println!("functional style: {}", sum_of_squared_odd_numbers);
}
Why does the closure for take_while take its argument by reference, while all the others take by value?
The implementation of Iterator::take_while is quite illuminating:
fn next(&mut self) -> Option<I::Item> {
if self.flag {
None
} else {
self.iter.next().and_then(|x| {
if (self.predicate)(&x) {
Some(x)
} else {
self.flag = true;
None
}
})
}
}
If the value returned from the underlying iterator were directly passed to the predicate, then ownership of the value would also be transferred. After the predicate was called, there would no longer be a value to return from the TakeWhile adapter if the predicate were true!

Conflicting lifetime requirements when storing closure capturing returned value

EDIT:
I'm trying to create a vector of closures inside a function, add a standard closure to the vector, and then return the vector from the function. I'm getting an error about conflicting lifetimes.
Code can be executed here.
fn vec_with_closure<'a, T>(f: Box<FnMut(T) + 'a>) -> Vec<Box<FnMut(T) + 'a>>
{
let mut v = Vec::<Box<FnMut(T)>>::new();
v.push(Box::new(|&mut: t: T| {
f(t);
}));
v
}
fn main() {
let v = vec_with_closure(Box::new(|t: usize| {
println!("{}", t);
}));
for c in v.iter_mut() {
c(10);
}
}
EDIT 2:
Using Rc<RefCell<...>> together with move || and the Fn() trait as opposed to the FnMut()m as suggested by Shepmaster, helped me produce a working version of the above code. Rust playpen version here.
Here's my understanding of the problem, slightly slimmed down:
fn filter<F>(&mut self, f: F) -> Keeper
where F: Fn() -> bool + 'static //'
{
let mut k = Keeper::new();
self.subscribe(|| {
if f() { k.publish() }
});
k
}
In this method, f is a value that has been passed in by-value, which means that filter owns it. Then, we create another closure that captures f by-reference. We are then trying to save that closure somewhere, so all the references in the closure need to outlive the lifetime of our struct (I picked 'static for convenience).
However, f only lives until the end of the method, so it definitely won't live long enough. We need to make the closure own f. It would be ideal if we could use the move keyword, but that causes the closure to also move in k, so we wouldn't be able to return it from the function.
Trying to solve that led to this version:
fn filter<F>(&mut self, f: F) -> Keeper
where F: Fn() -> bool + 'static //'
{
let mut k = Keeper::new();
let k2 = &mut k;
self.subscribe(move || {
if f() { k2.publish() }
});
k
}
which has a useful error message:
error: `k` does not live long enough
let k2 = &mut k;
^
note: reference must be valid for the static lifetime...
...but borrowed value is only valid for the block
Which leads to another problem: you are trying to keep a reference to k in the closure, but that reference will become invalid as soon as k is returned from the function. When items are moved by-value, their address will change, so references are no longer valid.
One potential solution is to use Rc and RefCell:
fn filter<F>(&mut self, f: F) -> Rc<RefCell<Keeper>>
where F: Fn() -> bool + 'static //'
{
let mut k = Rc::new(RefCell::new(Keeper::new()));
let k2 = k.clone();
self.subscribe(move || {
if f() { k2.borrow_mut().publish() }
});
k
}

How to handle multiple optionals in grammar

I would like to know how I can handle multiple optionals without concrete pattern matching for each possible permutation.
Below is a simplified example of the problem I am facing:
lexical Int = [0-9]+;
syntax Bool = "True" | "False";
syntax Period = "Day" | "Month" | "Quarter" | "Year";
layout Standard = [\ \t\n\f\r]*;
syntax Optionals = Int? i Bool? b Period? p;
str printOptionals(Optionals opt){
str res = "";
if(!isEmpty("<opt.i>")) { // opt has i is always true (same for opt.i?)
res += printInt(opt.i);
}
if(!isEmpty("<opt.b>")){
res += printBool(opt.b);
}
if(!isEmpty("<opt.p>")) {
res += printPeriod(opt.period);
}
return res;
}
str printInt(Int i) = "<i>";
str printBool(Bool b) = "<b>";
str printPeriod(Period p) = "<p>";
However this gives the error message:
The called signature: printInt(opt(lex("Int"))), does not match the declared signature: str printInt(sort("Int"));
How do I get rid of the opt part when I know it is there?
I'm not sure how ideal this is, but you could do this for now:
if (/Int i := opt.i) {
res += printInt(i);
}
This will extract the Int from within opt.i if it is there, but the match will fail if Int was not provided as one of the options.
The current master on github has the following feature to deal with optionals: they can be iterated over.
For example:
if (Int i <- opt.i) {
res += printInt(i);
}
The <- will produce false immediately if the optional value is absent, and otherwise loop once through and bind the value which is present to the pattern.
An untyped solution is to project out the element from the parse tree:
rascal>opt.i.args[0];
Tree: `1`
Tree: appl(prod(lex("Int"),[iter(\char-class([range(48,57)]))],{}),[appl(regular(iter(\char-class([range(48,57)]))),[char(49)])[#loc=|file://-|(0,1,<1,0>,<1,1>)]])[#loc=|file://-|(0,1,<1,0>,<1,1>)]
However, then to transfer this back to an Int you'd have to pattern match, like so:
rascal>if (Int i := opt.i.args[0]) { printInt(i); }
str: "1"
One could write a generic cast function to help out here:
rascal>&T cast(type[&T] t, value v) { if (&T a := v) return a; throw "cast exception"; }
ok
rascal>printInt(cast(#Int, opt.i.args[0]))
str: "1"
Still, I believe Rascal is missing a feature here. Something like this would be a good feature request:
rascal>Int j = opt.i.value;
rascal>opt.i has value
bool: true

Return a closure from a function

Note that this question pertains to a version of Rust before 1.0 was released
Do I understand correctly that it is now impossible to return a closure from a function, unless it was provided to the function in its arguments? It is very useful approach, for example, when I need the same block of code, parameterized differently, in different parts of program. Currently the compiler does not allow something like this, naturally:
fn make_adder(i: int) -> |int| -> int {
|j| i + j
}
The closure is allocated on the stack and is freed upon returning from a function, so it is impossible to return it.
Will it be possible to make this work in future? I heard that dynamically-sized types would allow this.
This can't ever work for a stack closure; it needs to either have no environment or own its environment. The DST proposals do include the possibility of reintroducing a closure type with an owned environment (~Fn), which would satisfy your need, but it is not clear yet whether that will happen or not.
In practice, there are other ways of doing this. For example, you might do this:
pub struct Adder {
n: int,
}
impl Add<int, int> for Adder {
#[inline]
fn add(&self, rhs: &int) -> int {
self.n + *rhs
}
}
fn make_adder(i: int) -> Adder {
Adder {
n: int,
}
}
Then, instead of make_adder(3)(4) == 7, it would be make_adder(3) + 4 == 7, or make_adder(3).add(&4) == 7. (That it is Add<int, int> that it is implementing rather than just an impl Adder { fn add(&self, other: int) -> int { self.n + other } is merely to allow you the convenience of the + operator.)
This is a fairly silly example, as the Adder might just as well be an int in all probability, but it has its possibilities.
Let us say that you want to return a counter; you might wish to have it as a function which returns (0, func), the latter element being a function which will return (1, func), &c. But this can be better modelled with an iterator:
use std::num::{Zero, One};
struct Counter<T> {
value: T,
}
impl<T: Add<T, T> + Zero + One + Clone> Counter<T> {
fn new() -> Counter<T> {
Counter { value: Zero::zero() }
}
}
impl<T: Add<T, T> + Zero + One + Clone> Iterator<T> for Counter<T> {
#[inline]
fn next(&mut self) -> Option<T> {
let mut value = self.value.clone();
self.value += One::one();
Some(value)
}
// Optional, just for a modicum of efficiency in some places
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(uint::max_value, None)
}
}
Again, you see the notion of having an object upon which you call a method to mutate its state and return the desired value, rather than creating a new callable. And that's how it is: for the moment, where you might like to be able to call object(), you need to call object.method(). I'm sure you can live with that minor inconvenience that exists just at present.

Resources