Julia function without name and with double parenthesis - syntax

This is a "beginning with Julia"-question.
I read some basic Julia function tutorials, but could
not yet find the sense of double parenthesis, like in
this example (from JuliaReinforcement RandomWalk1D):
function (env::RandomWalk1D)(action)
env.pos = max(min(env.pos + env.actions[action], env.N), 1)
end
What does the double parenthesis (without function name??) mean here?
When and how is this function called?
Thank you!

I assume you refer to the source of the package that can be found here.
This kind of definition creates a functor. See here in the documentation for an explanation.
The idea is simple. You want to be able to call a value just like you would call a function. Here is a minimal example:
julia> struct A
v
end
julia> (x::A)() = x.v
julia> a = A(100)
A(100)
julia> a()
100
Note that in this example a is a value, but still you can call it with a() as if it were a function.
If something is not clear please comment and I can expand on it.

Related

Julia: define method for custom type

I apologize if this has been answered before, I didn't find a straight answer for this among my search results.
I'm going through "Learn Julia The Hardway" and I can't really find where's the difference in my code vs the example in the book. Whenever I run it I get the following error:
TypeError: in Type{...} expression, expected UnionAll, got a value of type typeof(+)
Here's the code:
struct LSD
pounds::Int
shillings::Int
pence::Int
function LSD(l,s,d)
if l<0 || s<0 || d<0
error("No negative numbers please, we're british")
end
if d>12 error("That's too many pence") end
if s>20 error("That's too many shillings") end
new(l,s,d)
end
end
import Base.+
function +{LSD}(a::LSD, b::LSD)
pence_s = a.pence + b.pence
shillings_s = a.shillings + b.shillings
pounds_s = a.pounds + b.pounds
pences_subtotal = pence_s + shillings_s*12 + pounds_s*240
(pounds, balance) = divrem(pences_subtotal,240)
(shillings, pence) = divrem(balance,12)
LSD(pounds, shillings, pence)
end
Another quick question, I haven't got yet to the functions chapter, but it catches my attention that there is no "return" at the end of the functions, I'm guessing that if it isn't stated a function will return the last evaluated value, am I right?
This appears to be using very old Julia syntax (I think from version 0.6). I think you just want function +(a::LSD, b::LSD)

Why does _ destroy at the end of statement?

I've seen a few other questions and answers stating that let _ = foo() destroys the result at the end of the statement rather than at scope exit, which is what let _a = foo() does.
I am unable to find any official description of this, nor any rationale for this syntax.
I'm interested in a few inter-twined things:
Is there even a mention of it in the official documentation?
What is the history behind this choice? Is it simply natural fall-out from Rust's binding / destructuring rules? Is it something inherited from another language? Or does it have some other origin?
Is there some use-case this syntax addresses that could not have been achieved using explicit scoping?
Is it simply natural fall-out from Rust's binding / destructuring rules?
Yes. You use _ to indicate that you don't care about a value in a pattern and that it should not be bound in the first place. If a value is never bound to a variable, there's nothing to hold on to the value, so it must be dropped.
All the Places Patterns Can Be Used:
match Arms
Conditional if let Expressions
while let Conditional Loops
for Loops
let Statements
Function Parameters
Is there even a mention of it in the official documentation?
Ignoring an Entire Value with _
Of note is that _ isn't a valid identifier, thus you can't use it as a name:
fn main() {
let _ = 42;
println!("{}", _);
}
error: expected expression, found reserved identifier `_`
--> src/main.rs:3:20
|
3 | println!("{}", _);
| ^ expected expression
achieved using explicit scoping
I suppose you could have gone this route and made expressions doing this just "hang around" until the scope was over, but I don't see any value to it:
let _ = vec![5];
vec![5]; // Equivalent
// Gotta wait for the scope to end to clean these up, or call `drop` explicitly
The only reason that you'd use let _ = foo() is when the function requires that you use its result, and you know that you don't need it. Otherwise, this:
let _ = foo();
is exactly the same as this:
foo();
For example, suppose foo has a signature like this:
fn foo() -> Result<String, ()>;
You will get a warning if you don't use the result, because Result has the #[must_use] attribute. Destructuring and ignoring the result immediately is a concise way of avoiding this warning in cases where you know it's ok, without introducing a new variable that lasts for the full scope.
If you didn't pattern match against the result then the value would be dropped as soon as the foo function returns. It seems reasonable that Rust would behave the same regardless of whether you explicitly said you don't want it or just didn't use it.

Filter an collection of tuples

I'm playing with iterables and comprehension in Julia and tried to code simple problem: find all pairs of numbers less then 10 whose product is less then 10. This was my first try:
solution = filter((a,b)->a*b<10, product(1:10, 1:10))
collect(solution)
but I got error "wrong number of arguments". This is kind of expected because anonymous function inside filter expects two arguments but it gets one tuple.
I know I can do
solution = filter(p->p[1]*p[2]<10, product(1:10, 1:10))
but it doesn't look nice as the one above. Is there a way I can tell that (a,b) is argument of type tuple and use something similar to syntax in first example?
I don't think there's a way to do exactly as you'd like, but here are some alternatives you could consider for the anonymous function:
x->let (a,b)=x; a*b<10 end
x->((a,b)=x; a*b<10)
These can of course be made into macros if you like:
macro tup(ex)
#assert ex.head == :(->)
#assert ex.args[1].head == :tuple
arg = gensym()
quote
$arg -> ( $(ex.args[1]) = $arg; $(ex.args[2]) )
end
end
Then #tup (a, b) -> a * b < 10 will do as you like.
Metaprogramming in Julia is pretty useful and common for situations where you are doing something over and over and would like specialized syntax for it. But I would avoid this kind of metaprogramming if this were a one-off thing, because adding new syntax means learning new syntax and makes code harder to read.

What is the return type of my VBScript function?

This question is mostly out of interest to understand the functionality of VBScript better. I recognize that I can simply do some casting to know what to expect from my code, but in my situation I want to understand why casting, or any "workaround", is needed. For simplicity, here's the basic idea of my code:
variable1 = 1
Public Function findSomethingInATextString(par1, par2)
[...searching with a Do Until loop code here...]
Result = 1
If([par2 is found in par1]) Then
Result = 0
End If
Return Result
End Function
variable1 = findSomethingInATextString("Hello World", "Hello")
When I run this I get a Type Mismatch error. I don't understand why that's the case. variable1 is an integer and findSomethingInAString() returns an integer. They appear to be the same data type.
I'm working in a restricted environment where I can't do much debugging (it's painfully slow to code in this program...). So at the moment I'm unable to say what data type this is coming out as - I just know that it's apparently not integer.
After all that, and to make sure my question is clear, I'm intrigued to know what the return type of my function is (if someone happens to know), but my real question is: Why isn't the return type matching with variable1?
Use the minimal script
Return
Output
cscript 36633603.vbs
...36633603.vbs(1, 1) Microsoft VBScript runtime error: Type mismatch: 'return'
to prove to yourself, that just mentioning return in a VBScript will throw a type mismatch error.
Believe JosefZ's comment that VBScript returns function values by assigning to the function's name. Better: Read the docs (before you try to write code).
Evidence:
Function f1()
f1 = 1
End Function
WScript.Echo f1(), TypeName(f1())
Output:
cscript 36633603.vbs
1 Integer

Is Odersky serious with "bills !*&^%~ code!"?

In his book programming in scala (Chapter 5 Section 5.9 Pg 93)
Odersky mentioned this expression "bills !*&^%~ code!"
In the footnote on same page:
"By now you should be able to figure out that given this code,the Scala compiler would
invoke (bills.!*&^%~(code)).!()."
That's a bit to cryptic for me, could someone explain what's going on here?
What Odersky means to say is that it would be possible to have valid code looking like that. For instance, the code below:
class BadCode(whose: String, source: String) {
def ! = println(whose+", what the hell do you mean by '"+source+"'???")
}
class Programmer(who: String) {
def !*&^%~(source: String) = new BadCode(who, source)
}
val bills = new Programmer("Bill")
val code = "def !*&^%~(source: String) = new BadCode(who, source)"
bills !*&^%~ code!
Just copy&paste it on the REPL.
The period is optional for calling a method that takes a single parameter, or has an empty parameter list.
When this feature is utilized, the next chunk after the space following the method name is assumed to be the single parameter.
Therefore,
(bills.!*&^%~(code)).!().
is identical to
bills !*&^%~ code!
The second exclamation mark calls a method on the returned value from the first method call.
I'm not sure if the book provides method signatures but I assume it's just a comment on Scala's syntactic sugar so it assumes if you type:
bill add monkey
where there is an object bill which has a method add which takes a parameter then it automatically interprets it as:
bill.add(monkey)
Being a little Scala rusty, I'm not entirely sure how it splits code! into (code).!() except for a vague tickling of the grey cells that the ! operator is used to fire off an actor which in compiler terms might be interpretted as an implicit .!() method on the object.
The combination of the '.()' being optional with method calls (as Wysawyg explained above) and the ability to use (almost) whatever characters you like for naming methods, makes it possible to write methods in Scala that look like operator overloading. You can even invent your own operators.
For example, I have a program that deals with 3D computer graphics. I have my own class Vector for representing a 3D vector:
class Vector(val x: Double, val y: Double, val z: Double) {
def +(v: Vector) = new Vector(x + v.x, y + v.y, z + v.z)
// ...etc.
}
I've also defined a method ** (not shown above) to compute the cross product of two vectors. It's very convenient that you can create your own operators like that in Scala, not many other programming languages have this flexibility.

Resources