Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

자료 매번 검색하기 귀찮아서 만든 블로그

Julia - function 입력값 다루기 본문

Julia

Julia - function 입력값 다루기

쿠키아버님 2022. 2. 9. 00:19

Julia에서 함수의 입력값을 받을 때 인수의 type을 지정해주는 경우가 있는데,

 

이 함수에 들어오는 인수의 type에 따라 함수 구조를 바꾸고 싶다고 할 때, 

 

(내가) 기본적으로 만들어 왔던 구조는 if를 활용한 코딩이었다.

 

Ex)

function foo(InputType)
	if typeof(InputType)==Int64
    	#blah blah
    end
    if typeof(InputType)==Float64
    	#blah blah
    end
end

 

그런데 함수의 입력값에 ::를 사용하면 조금 더 예쁘고 간결한, 가독성 좋은 코드가 된다.

 

Ex)

function foo(::Int64, n)
    println("First argument is Int64 and n is $n !")
end

function foo(InputType::Float64, n)
    println("First argument is Float64 and n is $n !")
end

 

첫번째 인수를 직접적으로 사용하지 않을 경우 이름은 지정해주지 않아도 OK

 

Union 함수를 사용하면 여러가지 타입에 대한 기능을 만드는 것도 가능하다.

 

julia> function foo(::Union{Int64, Float64}, n) println(n) end
foo (generic function with 1 method)

julia> foo(3, "Hellllo")
Hellllo

julia> foo(3.5, "Hellllo")
Hellllo

julia> foo("a", "Hellllo")
ERROR: MethodError: no method matching foo(::String, ::String)
Closest candidates are:
  foo(::Union{Float64, Int64}, ::Any) at REPL[1]:1
Stacktrace:
 [1] top-level scope
   @ REPL[4]:1

 

만약 첫번째 인수에 원하지 않는 타입이 왔을 때, 예외처리를 하려면 .. 

function foo(::String, n)
    throw(ArgumentError("First argument is string !"))
end

julia> foo("a", 4)
ERROR: ArgumentError: First argument is string !
Stacktrace:
 [1] foo(#unused#::String, n::Int64)
   @ Main e:\Julia\Val.jl:16
 [2] top-level scope
   @ REPL[8]:1

 

ArgumentError 명령어를 사용하면 편하다.