logo

줄리아의 타입과 애노테이션 📂Julia

줄리아의 타입과 애노테이션

Code

julia> typeof(0)
Int64

julia> typeof(0.0)
Float64

julia> typeof(0 == 0.0)
Bool

julia> typeof(Bool)
DataType

julia> typeof(NaN)
Float64

julia> typeof(Inf)
Float64

julia> typeof('O')
Char

julia> typeof("Ohmygirl")
String

julia> typeof("O")
String

Julia implements a variety of types. $0$ and $0.0$ are the same $0$ but have different types, and as you can see, even the type Bool has a type called DataType. Similar to the C language, String is an array of Char, and it is distinguished by whether it uses double or single quotes.

julia> supertype(Int64)
Signed

julia> supertype(Signed)
Integer

julia> supertype(Integer)
Real

julia> supertype(Real)
Number

julia> supertype(Number)
Any

julia> supertype(Any)
Any

Using the supertype() function as shown above allows you to check the supertype of a type. All types are subtypes of the Any type. Any is convenient and highly productive because it encompasses everything, as the name suggests.

julia> x = ["o", -1, [7,'m'],3.0]
4-element Array{Any,1}:
   "o"
 -1
   Any[7, 'm']
  3.0

julia> typeof(x)
Array{Any,1}

julia> x[2] = 1.2
1.2

julia> typeof(x)
Array{Any,1}

julia> y = [0,1,1]
3-element Array{Int64,1}:
 0
 1
 1

julia> typeof(y)
Array{Int64,1}

julia> y[2] = 1.2
ERROR: InexactError: Int64(1.2)
Stacktrace:
 [1] Int64 at .\float.jl:710 [inlined]
 [2] convert at .\number.jl:7 [inlined]
 [3] setindex!(::Array{Int64,1}, ::Float64, ::Int64) at .\array.jl:847
 [4] top-level scope at REPL[39]:1

julia> typeof(y)
Array{Int64,1}

An array created with Any allows for easy assignment and manipulation of values, but this is not possible with an array defined as integers only. Julia is a strongly typed language, and by providing types to infer, it can enhance performance and prevent bugs at their source. Limiting types is called annotation, and it is advisable to optimize after confirming that the program is implemented. The main reason for using Julia is often its speed.

julia> function add1(a,b)
           return a+b
       end
add1 (generic function with 1 method)

julia> add1(1,2)
3

julia> add(1,2.0)
ERROR: UndefVarError: add not defined
Stacktrace:
 [1] top-level scope at REPL[43]:1

julia> function add2(a::Int64, b::Float64)
           return a+b
       end
add2 (generic function with 1 method)

julia> add2(1,2)
ERROR: MethodError: no method matching add2(::Int64, ::Int64)
Closest candidates are:
  add2(::Int64, ::Float64) at REPL[44]:1
Stacktrace:
 [1] top-level scope at REPL[45]:1

julia> add2(1,2.0)
3.0

Using :: to specify what exactly a variable is will throw an error if the types do not match. Performance naturally improves when such annotations are in place, eliminating the need for type checks.

Environment

  • OS: Windows
  • julia: v1.5.0