Friday 4 March 2016

Julia: Restrict function arguments to specific type

You can specify type of the arguments to a function using :: operator.

function sum(x::Float64, y::Float64)
Above function takes only Float64 arguments.

julia> function sum(x::Float64, y::Float64)
           x+y
       end
sum (generic function with 1 method)

julia> sum(23.45, 43.56)
67.01


Since Julia is strongly typed language, you can’t call sum function with other type of arguments like integer, string etc.,. If you call function sum with integer arguments, you will receive MethodError.

julia> sum(10, 20)
ERROR: MethodError: `sum` has no method matching sum(::Int64, ::Int64)

julia> sum(10, 20.3)
ERROR: MethodError: `sum` has no method matching sum(::Int64, ::Float64)
Closest candidates are:
  sum(::Float64, ::Float64)



Previous                                                 Next                                                 Home

No comments:

Post a Comment