Can we use user input to assign variables in Julia? - julia

ans=readline(stdin)
function g(n)
if ans==a
return 1
else
return n
end
This is my code but the readline function only takes strings and i want it to take an expression which i can use in my function. What i want is to assign an expression (a) for variable ans.

You could try something like this:
julia> function check(x)
ans = readline()
val=Main.eval(Meta.parse(ans))
println("val == $x :", val==x)
end;
julia> check(5)
2+3
val == 5 :true
Remarks:
Your functions should not reference global variables (like ans in your example) - if you need to get the value of ans - pass it as parameter.
Parsing the expression is unsafe - a user might want for an example use this functionality to delete your data. Use with care! In some scenarios you might want for an example to use regular expressions to validate user's input.

Related

Julia Macro to Save the Overt form of a Function, and Define it

Some of the parameters to a simulation I am writing are functions. When the output is generated, I want to put the definition of these functional parameters in the output. I have in mind a macro that somehow saves the definition as a string, and then defines it. For example, here's what I do now:
borda_score_fn(p) = exp(1/p)
global g_borda_score_fn_string = "exp(1/p)"
And then I write g_borda_score_fn_string to my output. But this is really ugly!
What I would like to do is something like this:
#paramfn borda_score_fn(p) = exp(1/p)
And later be able to both call borda_score_fn(p), and have the form (i.e., "exp(1/p)") available for writing to my output log. (The string form might get stashed in a global dict, actually, they both could.)
I have tried many version of this, but can't get the right set of parses and calls to get it to work. Any help would be appreciated.
This may be a bit different than what you have in mind, but one perhaps "Julian" approach might be to have the function itself return the form string via multiple dispatch, rather than defining a whole new global variable just for that. For example, say we have a type
struct Form end
that we can use for dispatch, then we can write
borda_score_fn(p) = exp(1/p)
borda_score_fn(::Form) = "exp(1/p)"
which can then be retrieved just by calling the function with our type
julia> borda_score_fn(2)
1.6487212707001282
julia> borda_score_fn(Form())
"exp(1/p)"
That might actually be not bad on its own. But, if you want a macro to do both parts at once, then something along the lines of
macro paramfn(e)
name = esc(e.args[1].args[1])
str = string(e.args[2].args[2])
f = esc(e)
quote
$name(::Form) = $str
$f
end
end
would let you write
julia> #paramfn borda_score_fn(p) = exp(1/p)
borda_score_fn (generic function with 2 methods)
julia> borda_score_fn(1)
2.718281828459045
julia> borda_score_fn(Form())
"exp(1 / p)"
For completeness, here's how you can do it in a way more similar to your original approach, but more idiomatically than with a global variable:
julia> module FormOf
export formof, #paramfn
function formof end
macro paramfn(expr)
name = esc(expr.args[1].args[1])
form_str = string(expr.args[2].args[2])
quote
$(esc(expr))
$FormOf.formof(::typeof($name)) = $form_str
$name
end
end
end
Main.FormOf
julia> FormOf.#paramfn borda_score_fn(p) = exp(1/p)
borda_score_fn (generic function with 1 method)
julia> FormOf.formof(borda_score_fn)
"exp(1 / p)"
However, since it defines a new method of FormOf.formof, this only works in global scope:
julia> function bla()
FormOf.#paramfn fn(p) = exp(1/p)
fn(10) + 1
end
ERROR: syntax: Global method definition around REPL[45]:10 needs to be placed at the top level, or use "eval".
Stacktrace:
[1] top-level scope
# REPL[50]:1
#cbk's solution does not have this limitation.

function return in R programming language

I need help on returning a value/object from function
noReturnKeyword <- function(){
'noReturnKeyword'
}
justReturnValue <- function(){
returnValue('returnValue')
}
justReturn <- function(){
return('justReturn')
}
When I invoked these functions: noReturnKeyword(), justReturnValue(), justReturn(), I got output as [1] "noReturnKeyword", [1] "returnValue", [1] "justReturn" respectively.
My question is, even though I have not used returnValue or return keywords explicitly in noReturnKeyword() I got the output (I mean the value returned by the function).
So what is the difference in these function noReturnKeyword(), justReturnValue(), justReturn()
What is the difference in these words returnValue('') , return('')? are these one and the same?
When to go for returnValue('') and return('') in R functions ?
In R, according to ?return
If the end of a function is reached without calling return, the value of the last evaluated expression is returned.
return is the explicite way to exit a function and set the value that shall be returned. The advantage is that you can use it anywhere in your function.
If there is no explicit return statement R will return the value of the last evaluated expression
returnValueis only defined in a debugging context. The manual states:
the experimental returnValue() function may be called to obtain the
value about to be returned by the function. Calling this function in
other circumstances will give undefined results.
In other words, you shouldn't use that except in the context of on.exit. It does not even work when you try this.
justReturnValue <- function(){
returnValue('returnValue')
2
}
This function will return 2, not "returnValue". What happened in your example is nothing more than the second approach. R evaluates the last statement which is returnValue() and returns exactly that.
If you use solution 1 or 2 is up to you. I personally prefer the explicit way because I believe it makes the code clearer. But that is more a matter of opinion.

Progress 4GL In-line functions / Multi-line statement

Description:
I am Writing/Editing a LinqToProgress query engine. So far simple functions within progress is simple to replicate, such as "A" >= "B" or Lookup(A, B) > 1, simple one liners that give boolean conditions. However to implement more advance function or custom functions I will need to be able to write multiline statements that can be plugged into conditions, meaning the inline function should be able to give a boolean result when you use DISP ( myFunc ) in the ABL ScratchPad (Using Eclipse) or similar programs.
Issue:
I need to convert the code between the //Start Here and //End Here to an inline boolean result.
DEF VAR i AS INT NO-UNDO.
DEF VAR LIST AS CHAR NO-UNDO INIT "one,two,three,four".
DEF VAR LIST2 AS CHAR NO-UNDO INIT "one,three,five".
DISP(
// Start Here
DO i=1 TO NUM-ENTRIES(LIST):
IF LOOKUP(ENTRY(i, LIST),LIST2) > 0 THEN RETURN TRUE.
END.
RETURN FALSE.
// End Here
)
Currently the code throws an error.
White space after colon ends statement. I tried looking for solutions on multiline statements/inline functions but so far found nothing.
Constraints:
Everything written needs to be contained within the Disp function.
I can't use previously created functions.
You should introduce a method or function that contains your code block. The ABL does not support statements and blocks as an expression.

constrain argument to be in a set of values in Julia function signature

Is there a way in Julia to specify that a function argument can take one of a set of values through type annotations? For example, let's say I have function foo which accepts a single argument
function foo(x::String)
print(x)
end
the argument x can only be a String. Is there a way to further constrain it in the function signature so that it can only be for example one of the strings "right", "left", or "center"?
In Julia, the motto should be "There's a type for that!".
One way of handling this would be to create a type with a constructor that only allows the values you want (and possibly stores them in a more efficient manner).
Here is one example:
const directions = ["left", "right", "center"]
immutable MyDirection
Direction::Int8
function MyDirection(str::AbstractString)
i = findnext(directions, str, 1)
i == 0 && throw(ArgumentError("Invalid direction string"))
return new(i)
end
end
Base.show(io::IO, x::MyDirection) = print(io, string("MyDirection(\"",directions[x.Direction],"\")"))
function foo(x::MyDirection)
println(x)
end
function foo(str::AbstractString)
x = MyDirection(str)
println(x)
end
test = MyDirection("left")
foo(test)
foo("right")
Note: my example is written with Julia 0.4!
Edit:
Another approach would be to use symbols, such as :left, :right, and :center,
instead of strings.
These have the advantage of being interned (so that they can be compared simply by comparing their address), and they can also be used directly for type parameters.
For example:
immutable MyDirection{Symbol} ; end
function MyDirection(dir::Symbol)
dir in (:left, :right, :center) || error("invalid direction")
MyDirection{dir}()
end
MyDirection(dir::AbstractString) = MyDirection(symbol(dir))
That will let you do things like:
x = MyDirection("left")
which will create an immutable object of type MyDirection{:left}.
No, it is not. That would be dispatching on values, which isn't possible in Julia.
I'm not sure what your actual application is, but there are some possibly-appropriate workarounds to this, e.g.
abstract Sam81Args
type ArgRight <:Sam81Args end
type ArgLeft <:Sam81Args end
type ArgCenter <:Sam81Args end
function foo{T<:Sam81Args}(x::Type{T})
println(T)
end
foo(ArgCenter)

How can one store a binary operator in a variable?

I am pretty confused about the meaning of the %Something% operators.
How can one store a binary operator in a variable?
Something like...
binary_operator = store.binary(%in%)
c(3,9,4,1,7) binary_operator c(1:5) # would behave alike "c(3,9,4,1,7) %in% c(1:5)"
or something like
library(foreach)
binary_operator = expression(%do%) # or expression(%dopar%)
...
...
foreach (i=1:6) binary_operator { # would behave alike "foreach (i=1:6) %do% ..."
...
...
}
If you want to define your own infix operator, it must begin and end with %. This is so the parser knows how to properly pass the parameters to the function since it not the usual way code is parsed. Also, use the backtick to escape the percent signs in the variable name.
`%binary_operator%` <- `%in%`
c(3,9,4,1,7) %binary_operator% c(1:5)

Resources