Is there a higher-order range pattern that concatenates two or more InputRanges?
Something like
foreach (e; a) {
// do stuff with e
}
foreach (e; b) {
// do stuff with e
}
...
should instead be written as
foreach (e; someMagic(a, b, ...)) {
// do stuff with e
}
someMagic is chain from std.range: http://dlang.org/phobos/std_range.html#chain
Related
Underline _ cannot work for some scenario in following code:
case class Item
(
para: Int
)
val a = List(1, 2)
val b = List(Item(1), Item(2))
a foreach {
perA => println(perA * 2) // Line A: ok
}
a foreach {
println(_) // Line B: ok
}
a foreach {
println(_ * 2) // Line C: not ok
}
b foreach {
perB => println(perB.para) // line D: ok
}
b foreach {
println(_.para) // line E: not ok
}
Could someone explain for me about line C & line E, thanks.
TL;DR: the argument of the lambda can be inserted at an unexpected position. Instead of taking
a foreach { println(_.blah) }
and building
a foreach { x => println(x.blah) }
out of it, the compiler instead builds
a foreach { println( x => x.blah ) }
and then fails to derive the type for the argument x.
A) This is the most explicit way to write down the lambda, the only way to make it clearer would be to add a type:
a foreach { perA => println(perA * 2) }
is the same as
a foreach { (x: Int) => println(x * 2) }
This should obviously work.
B) This works because it's one way to write down the function automatically generated from println. It is equivalent to any of the six variants below:
a foreach { (x: Int) => println(x) }
a foreach { x => println(x) }
a foreach { println(_) }
a foreach { println _ }
a foreach { println }
a foreach println
C) Because of the * 2, this here
a foreach { println(_ * 2) }
can no longer be considered just println(_). Instead, it is interpreted as
a foreach { println( { (x: ??!) => x * 2 } ) }
and since println takes no function-valued arguments, it cannot determine what the type of x is supposed to be, and exits with an error.
D) Is essentially the same as A, it works, I hope it's clear.
E) Is a variation of C, but this time, the type-checker isn't looking for something with method *(i: Int), but instead it's looking for something with a member para.
This here:
b foreach { println(_.para) }
is again interpreted as a foreach with a function which ignores elements of b and returns the constant value of the expression println(_.para),
that is:
b foreach { println( { (x: ??!) => x.para } ) }
Again, the inner expression println( { (x: ??!) => x.para } ) does not make any sense, because println does not expect function-valued arguments (it can handle Any, but it's not enough to derive the type of x).
Suppose l = List(1, 2, 3):
scala> l foreach { println _ }
1
2
3
scala> l foreach { println }
1
2
3
l foreach { println _ } <=> l foreach { println } because _ can be omitted. But why does the following also produces the same result?
scala> l foreach { println(_) }
1
2
3
Shouldn't the _ be bounded to println instead of foreach?
in other words:
l foreach { println(_) } <=> l foreach { println(x => x) }
and therefore throws an error on missing parameter type?
l foreach { println(_.toString) } produces the expected missing parameter type error
foreach takes a function A => Unit, in this case, Int => Unit
println satisfies this condition, but it is a method, not a function. Scala can get around this though, through a technique called eta expansion. It creates a function that takes the inputs for the method and called the method with those inputs. In your case, it looks similar to (x: Int) => println(x).
Each way you've written accomplishes this.
l foreach { println }
Here Scala is able to infer that you want to treat println as a function and pass it to foreach
l foreach { println _ }
By adding the underscore you explicitly saying that you want to turn the method into a function
l foreach { println(_) }
This is similar to the last, for any method you call, you can use an underscore instead of passing a parameter. By doing this, instead of calling the method you create a partially-applied function. You then pass this function to foreach
l foreach { println(_.toString) }
This is quite a bit different. _.toString creates a function A => String but Scala cannot figure out the correct type for A. Another problem is not you are passing a value to println, so you are calling println and passing the result to foreach instead of turning it into a function. println returns Unit which is the wrong type to pass to foreach
Shouldn't the _ be bounded to println instead of foreach? in other words:
l foreach { println(_) } <=> l foreach { println(x => x) }
No, this is specifically excluded by rules for placeholders in anonymous functions:
An expression e of syntactic category Expr binds an underscore section u, if the following two conditions hold: (1) e properly contains u, and (2) there is no other expression of syntactic category Expr which is properly contained in e and which itself properly contains u.
"Properly contains" means _ never binds itself, and so it never expands to x => x. In your last example, _.toString does properly contain _ and so satisfies both conditions above.
You're forgetting that println(x) can also be written as println x in Scala. If there's only a single argument, the parenthesis are optional.
Using a simple recursive macro like the example below, its common to take the first argument, then glob the rest.
macro_rules! count_tts {
() => {0usize};
($_head:tt $($tail:tt)*) => {1usize + count_tts!($($tail)*)};
}
Is there a way to recursively take the last argument?
This makes it possible to:
Handle the arguments in reverse.
Take all the previous arguments into account (count them for example, see related question)
Something like ($($head:tt)* $tail:tt) ... but this doesn't work.
There is no "backtracking" in the macro parser, so no you can't do this directly with $($head:tt)* $tail:tt. But you can do it by reversing it yourself.
macro_rules! concat_reverse {
([] $($reversed:tt)*) => {
concat!($(stringify!($reversed)),*) // base case
};
([$first:tt $($rest:tt)*] $($reversed:tt)*) => {
concat_reverse!([$($rest)*] $first $($reversed)*) // recursion
};
}
fn main() {
println!("{}", concat_reverse!([e d c b a]))
// output: abcde
}
The macro trace looks like:
concat_reverse!([e d c b a])
== concat_reverse!([d c b a] e)
== concat_reverse!([c b a] d e)
== concat_reverse!([b a] c d e)
== concat_reverse!([a] b c d e)
== concat_reverse!([] a b c d e)
== concat!(stringify!(a), stringify!(b), stringify!(c), stringify!(d), stringify!(e))
You could do some "map" and "reduce" operation (e.g. for counting) in the recursion phase.
Note that this method will eat your recursion depth, you may need to raise your #![recursion_limit="..."].
In C, I'm used to having:
if (ELEM(value, a, b, c)) { ... }
which is a macro with a variable number of arguments to avoid typing out
if (value == a || value == b || value == c) { ... }
A C example can be seen in Varargs `ELEM` macro for use with C.
Is this possible in Rust? I assume it would use match. If so, how would variadic arguments be used to achieve this?
macro_rules! cmp {
// Hack for Rust v1.11 and prior.
(#as_expr $e:expr) => { $e };
($lhs:expr, $cmp:tt any $($rhss:expr),*) => {
// We do this to bind `$lhs` to a name so we don't evaluate it multiple
// times. Use a leading underscore to avoid an unused variable warning
// in the degenerate case of no `rhs`s.
match $lhs { _lhs => {
false || $(
cmp!(#as_expr _lhs $cmp $rhss)
) || *
// ^- this is used as a *separator* between terms
}}
};
// Same, but for "all".
($lhs:expr, $cmp:tt all $($rhss:expr),*) => {
match $lhs { _lhs => {
true && $( cmp!(#as_expr _lhs $cmp $rhss) ) && *
}}
};
}
fn main() {
let value = 2;
if cmp!(value, == any 1, 2, 3) {
println!("true! value: {:?}", value);
}
if cmp!(value*2, != all 5, 7, 1<<7 - 1) {
println!("true! value: {:?}", value);
}
}
First off, if your a, b, and c are concrete values, you can just use match:
fn main() {
let x = 42;
match x {
1 | 2 | 3 => println!("foo"),
42 => println!("bar"),
_ => println!("nope"),
}
}
If you want to match on variables you need to write the match arms like this:
match x {
x if x == a || x == b || x == c => println!("foo"),
42 => println!("bar"),
_ => println!("nope"),
}
…which is basically what you want to avoid.
But: A pretty direct translation of your C macro is also possible!
macro_rules! elem {
($val:expr, $($var:expr),*) => {
$($val == $var)||*
}
}
fn main() {
let y = 42;
let x = 42;
if elem!(x, 1, 3, y) {
println!("{}", x);
}
}
I'm partial to writing this without a macro, taking advantage of contains on arrays.
fn main() {
if [1, 2, 3, 4].contains(&4) {
println!("OK");
}
}
It's hard to predict what will happen to this when optimized, but if absolute performance is a goal you'd do well to benchmark each approach.
Yes this is possible, the following macro expands to do each check.
macro_rules! elem {
($n:expr, $( $hs:expr ),*) => ($( $n == $hs )||* );
}
fn main() {
if elem!(4, 1, 2, 3, 4) {
println!("OK");
}
}
Thanks to #vfs on #rust in IRC.
In scala we can use for loops as follows:
for { a <- someCollection
b = a.someFunc} //inbody we can use b
I need similar functionality with a while loop for example:
while({ val a = someFunction
a.isDefined }) { //do something with a in body }
How can I do this in scala?
EDIT
I know we can do this using a var on top and modifying it within the loop but I was looking for something more elegant.
What I wish to accomplish is as follows. The function someFunction iterates over a collection of Options and check for the item that is not a None. If it does not find such an option it returns a None. I can probably do this using
for( a <- myCollection
if a.isDefined) {}
but in this case I dont make use of my function.
You could write your own extended while function, like:
def extendedWhile[T](condFunc: => Option[T])(block: T => Unit): Unit = {
val a = condFunc
if (a.isDefined) {
block(a.get)
extendedWhile(condFunc)(block)
}
}
Which can be used as:
def rand =
if ((new scala.util.Random).nextFloat < 0.4) None
else Some("x")
extendedWhile(rand) {
x => println(x)
}
// prints out x a random amount of times
This extendedWhile function is tail recursive, so it should normally be as performant as the regular while loop.
I am not sure I like this, but one way to do this is to define the variable as 'var' outside the loop.
var a: Boolean = _;
def someFunction: Boolean = true
while({ a = someFunction; a }) {
println("hi " + a)
}
For is actually syntactic sugar for foreach, map, and flatMap.
So your code above desugars to:
someCollection.map { a=> f(a)}.foreach {b => ... //something using b}
Now, while is not a desugaring, but an actual imperative syntactic construct.
So the best you can do is
var a = true
while (a) {
a = someFunction (a)
}
In practice I never find myself using while, and instead use higher-order functions: like
input.takeWhile(_ != '').foreach { //do something }