Functions in Julia are first_class objects

1. They can be assigned to variables, called using the standard function call syntax from the variable they have been assigned to.
2. They can be used as arguments, and they can be returned as values.
3. They can also be created anonymously, without being given a name

1. Function
2. Inplementation
3. Arguments
4. Anonymous Function

 
1. Function

julia> +      # Julia에서는 operator들은 함수의 성질을 가진다.
+ (generic function with 92 methods)

julia> !
! (generic function with 3 methods)

julia> +(1,2,3,4,5)
15

julia> h = +
+ (generic function with 92 methods)

julia> h(1,2,3)
6

 

2. Inplementation

julia>          # 기본 함수 문법
function f(x,y)
x+y   # return 구문이 없을 때, 마지막 줄에서 evaluation 된 value가 return 값이 된다.
end
f (generic function with 1 method)

julia> f(2,3)
5

 

julia> f(x,y) = 2x+y      # 간략하게 함수 구현 가능
f (generic function with 1 method)

julia> f(2,3)
7

 

julia> function div(a, b)     # 하나의 함수가 2개 이상의 리턴값을 가질 수 있다.
fld(a,b), mod(a,b)         # 몫과 나머지
end

julia> a = div(35, 8)          # return 값은 Tuple 형태로 반환된다.
(4,3)

 

julia>
function create_adder(x)             # Internal function
function adder(y)
return x+y
end
return adder                                        # return function
end
create_adder (generic function with 1 method)

julia> a = create_adder(10)
adder (generic function with 1 method)

julia> a(5)
15

 

3. Arguments

julia> bar(a, b, x…) = (a, b, x)                    # 가변인자 함수 (Varargs Functions)
bar (generic function with 2 methods)       #  변수명 뒤에 점 3개로 tuple type으로 매개변수 설정

julia> bar(1,2)
(1,2,())

julia> bar(1,2,3,4,5)
(1,2,(3,4,5))

 

julia>
function decorate_name( name, c=’#’, rep=6)
println(string(c)^rep)
println(name)
end
decorate_name (generic function with 3 methods)

julia> decorate_name(“sosal”)
######
sosal

julia> decorate_name(“sosal”,’*’, 12)
************
sosal

 

 

4. Anonymous Function

julia> map( y -> y^2 + 2y + 1, [1,2,3,4] ) # Create function anonymously, without being given a name
4-element Array{Int64,1}:

julia> reduce( +, [4, 9, 16, 25] )
54

julia> mapreduce( x -> x^2 + 2x + 1 , +, [1,2,3,4])
54