Ternary operator and range in Julia - julia

I went to this error by chance which I fixed with some diverted way, but still I was curious how it is solved for Julia.
Suppose the MWE:
julia> a = 1 ; b = 5 ; some_logical_value = true
julia> #assert a > 0 ? b in 1:10 : some_logical_value
ERROR: syntax: space required before colon in "?" expression
Stacktrace:
[1] top-level scope at none:1
Which yields an error as, not surprisingly : from ternary operator and : from 1:10 is misleading for Julia. How should we do so?

You just need to add parentheses enclosing the range expression, so either of
#assert a > 0 ? b in (1:10) : some_logical_value
or
#assert a > 0 ? (b in 1:10) : some_logical_value
should work.

Related

Creating subset using or statement

I have a data frame with 6 columns and thousands of rows containing share transactions. I want to identify rows with bad price data. The following function gives me a subset with the rows with good price data:
function in_price_range(df)
price_good = subset(df, :UnitPrice => X-> (trough_share_price .<= X .<= peak_share_price), skipmissing=true)
return price_good
end
For a subset for bad data I tried:
function out_price_range(df)
price_discrepancy = subset(df, :UnitPrice => X-> (X .< trough_share_price || X .> peak_share_price), skipmissing=true)
return price_discrepancy
end
However, that givers error TypeError: non-boolean (BitVector) used in boolean context
I tried .|| rather than || but that then gives error: syntax: "|" is not a unary operator
How do I fix the code?
In Julia, || is
help?> ||
search: ||
x || y
Short-circuiting boolean OR.
The short-circuiting part meaning, that if x is true, || will not even bother to evaluate y. In other words, this will make a branch in the code. For example:
julia> 5 < 7 || print("This is unreachable")
true
This is great if you want to write code that is efficient for a case like
if something_easy_to_evaluate || something_costly_to_evaluate
# Do something
end
In other words, this is control flow! Obviously, this cannot be broadcasted. For that, what you want is the regular or operator |, which you can broadcast with .|. So for example:
julia> a = rand(3) .< 0.5
3-element BitVector:
1
0
0
julia> b = rand(3) .< 0.5
3-element BitVector:
0
1
0
julia> a .|| b
ERROR: syntax: "|" is not a unary operator
Stacktrace:
[1] top-level scope
# none:1
julia> a .| b
3-element BitVector:
1
1
0
The same applies to && vs &; the former is only used for control-flow, the latter is normal bitwise and.

Julia Metaprogramming: Function for Mathematical Series

I'm trying to build a function that will output an expression to be assigned to a new in-memory function. I might be misinterpreting the capability of metaprogramming but, I'm trying to build a function that generates a math series and assigns it to a function such as:
main.jl
function series(iter)
S = ""
for i in 1:iter
a = "x^$i + "
S = S*a
end
return chop(S, tail=3)
end
So, this will build the pattern and I'm temporarily working with it in the repl:
julia> a = Meta.parse(series(4))
:(x ^ 1 + x ^ 2 + x ^ 3 + x ^ 4)
julia> f =eval(Meta.parse(series(4)))
120
julia> f(x) =eval(Meta.parse(series(4)))
ERROR: cannot define function f; it already has a value
Obviously eval isn't what I'm looking for in this case but, is there another function I can use? Or, is this just not a viable way to accomplish the task in Julia?
The actual error you get has to do nothing with metaprogramming, but with the fact that you are reassigning f, which was assigned a value before:
julia> f = 10
10
julia> f(x) = x + 1
ERROR: cannot define function f; it already has a value
Stacktrace:
[1] top-level scope at none:0
[2] top-level scope at REPL[2]:1
It just doesn't like that. Call either of those variables differently.
Now to the conceptual problem. First, what you do here is not "proper" metaprogramming in Julia: why deal with strings and parsing at all? You can work directly on expressions:
julia> function series(N)
S = Expr(:call, :+)
for i in 1:N
push!(S.args, :(x ^ $i))
end
return S
end
series (generic function with 1 method)
julia> series(3)
:(x ^ 1 + x ^ 2 + x ^ 3)
This makes use of the fact that + belongs to the class of expressions that are automatically collected in repeated applications.
Second, you don't call eval at the appropriate place. I assume you meant to say "give me the function of x, with the body being what series(4) returns". Now, while the following works:
julia> f3(x) = eval(series(4))
f3 (generic function with 1 method)
julia> f3(2)
30
it is not ideal, as you newly compile the body every time the function is called. If you do something like that, it is preferred to expand the code once into the body at function definition:
julia> #eval f2(x) = $(series(4))
f2 (generic function with 1 method)
julia> f2(2)
30
You just need to be careful with hygiene here. All depends on the fact that you know that the generated body is formulated in terms of x, and the function argument matches that. In my opinion, the most Julian way of implementing your idea is through a macro:
julia> macro series(N::Int, x)
S = Expr(:call, :+)
for i in 1:N
push!(S.args, :($x ^ $i))
end
return S
end
#series (macro with 1 method)
julia> #macroexpand #series(4, 2)
:(2 ^ 1 + 2 ^ 2 + 2 ^ 3 + 2 ^ 4)
julia> #series(4, 2)
30
No free variables remaining in the output.
Finally, as has been noted in the comments, there's a function (and corresponding macro) evalpoly in Base which generalizes your use case. Note that this function does not use code generation -- it uses a well-designed generated function, which in combination with the optimizations results in code that is usually equal to the macro-generated code.
Another elegant option would be to use the multiple-dispatch mechanism of Julia and dispatch the generated code on type rather than value.
#generated function series2(p::Val{N}, x) where N
S = Expr(:call, :+)
for i in 1:N
push!(S.args, :(x ^ $i))
end
return S
end
Usage
julia> series2(Val(20), 150.5)
3.5778761722367333e43
julia> series2(Val{20}(), 150.5)
3.5778761722367333e43
This task can be accomplished with comprehensions. I need to RTFM...
https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions

LoadError: syntax: unexpected "end" in expression starting at untitled-

I'm getting started with the Julia programming language and I'm not really understanding the "end" syntax.
function foo(s, d, m)
res = 0
for i in range(0,length(s)-m)
tmp = 0
for j in range(0,m)
tmp += s[i+m]
end
if tmp == d
res++
end
end
return res
end
Running this code I get
LoadError: syntax: unexpected "end"
in expression starting at untitled-eae5b84e07787c95497e056f34423071:10
How should I fix my function?
Julia does not increment with res++. Instead, write
res += 1

Keyword Arguments - Functions

I am a beginner in Julia,
how can I create functions with keywords for arguments without having to initialize these arguments in function?
A very simple example:
function f(;a = 1, b = 2)
a+b
end
I would like to do:
function f(;a, b)
a+b
end
Best regards.
This is a new feature in version 0.7 — you can actually write it just as you'd like.
Julia's syntax on versions 0.6 and prior require you to give them a default value, but since that default value is evaluated at call time, you can actually use an error function to require them:
julia> function f(;a=error("a not provided"), b=error("b not provided"))
a+b
end
f (generic function with 1 method)
julia> f()
ERROR: a not provided
Stacktrace:
[1] f() at ./REPL[1]:2
julia> f(a=2)
ERROR: b not provided
Stacktrace:
[1] (::#kw##f)(::Array{Any,1}, ::#f) at ./<missing>:0
julia> f(a=2, b=3)
5
This is comming in Julia 0.7 line:
Keyword arguments can be required: if a default value is omitted, then an exception is thrown if the caller does not assign the keyword a value (#25830).
So:
function f(;a, b)
a+b
end
Will become syntax sugar for:
function f(;a = throw(UndefKeywordError(:a)), b = throw(UndefKeywordError(:b)))
a+b
end
Another workaround is to create a function with variadic keyword arguments and leave any requirements over the expected keyword inputs as assertions inside the code. E.g.
function f( ; kwargs... )
V = Dict( kwargs )
try; assert( haskey( V, :a ) ); assert( haskey( V, :b ) )
catch e; throw( AssertionError("KWargs need to be a and b") )
end
V[:a] + V[:b]
end
f(a=1, b=2) #> 3
f(a=1, c=2) #> ERROR: AssertionError: KWargs need to be a and b
Or even as simple as:
function f( ; kwargs... )
V = Dict( kwargs )
a = V[:a]
b = V[:b]
a + b
end
f(a=1, c=2) #> ERROR: KeyError: key :b not found
Disclaimer: I'm not recommending this, I'm just saying it's another workaround to consider depending on what functionality you have in mind.

R operator overloading

Does anyone know how to overload the [] operator in R?
`[]` <- function(a, b) a + b
x = 5
y = 5
x[]y
Error: unexpected symbol in "x[]y"
R operator overloading seems to work for all other symbols except the []and ().

Resources