tryingHard
tryingHard

Reputation: 2084

Anonymous function Julia - value of x

I don't understand from where is x initialized, cause it is used in comparision next.

I tried showing value of x or a.

I have this code:

a = x -> ifelse(ε > x, 1, ifelse(ε < -x, -1, 0))
println(a)

The x is not initialized before - what does this code? Is x random number from normal distribution with mean 0?

Upvotes: 2

Views: 512

Answers (2)

Steven Siew
Steven Siew

Reputation: 871

Functions in Julia are first-class objects: they can be assigned to variables, and called using the standard function call syntax from the variable they have been assigned to. They can be used as arguments, and they can be returned as values. They can also be created anonymously, without being given a name, using either of these syntaxes:

Consider a simple function below

 function MyPlus(x,y)
       x + y
 end

The anonymous version of the function is

a = (x,y) -> x + y

So what we have is

the symbol a represent the variable a which contains a function. Specifically it contains the anonymous function

the symbol x represents a DUMMY VARIABLE which is used to construct an anonymous function. It has NO VALUE outside the definition of the anonymous function

the symbol y represents a DUMMY VARIABLE which is used to construct an anonymous function. It has NO VALUE outside the definition of the anonymous function

Since both x and y are DUMMY VARIABLES, they do not need to be initialised and they contain no value outside of the definition of the anonymous function. Infact they do not even exists outside the definition of the anonymous function.

There is nothing special about x and y, you can usse any symbol, including

mama = (baby,toy) -> baby + toy

Upvotes: 0

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

Here is a simplified version of code you are referring to:

θ = zeros(1000) # or some other vector
ε = randn()
sum(x -> ifelse(ε > x, 1, ifelse(ε < -x, -1, 0)), θ)

Now x -> ifelse(ε > x, 1, ifelse(ε < -x, -1, 0)) defines an anonymous function that takes one argument x and returns -1 if x is less than , 1 if it is greater than ε and otherwise it returns 0.

Then one of the methods of sum function in Julia accepts two arguments, a function and a collection. The way it works is that it applies the anonymous function x -> ifelse(ε > x, 1, ifelse(ε < -x, -1, 0)) to each element of θ and calculates the sum of the return values.

EDIT

Alternatively you could define this code e.g. as

sum(ifelse(ε > x, 1, ifelse(ε < -x, -1, 0)) for x in θ)

Upvotes: 3

Related Questions