자료 매번 검색하기 귀찮아서 만든 블로그
Julia - function 입력값 다루기 본문
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 명령어를 사용하면 편하다.
'Julia' 카테고리의 다른 글
Julia - sizehint! (0) | 2022.02.13 |
---|---|
Julia에서 행렬을 1차원 배열로 만들기 (0) | 2022.02.13 |
Julia - conditional operators (0) | 2022.02.11 |
recipe 사용하기 (0) | 2022.02.09 |
Julia - VectorOfArray 사용하기 (배열의 배열을 1차원 배열로 변환) (0) | 2021.12.04 |