How to write “good” Julia code when dealing with multiple types and arrays (multiple dispatch)

前端 未结 2 1798
抹茶落季
抹茶落季 2020-12-29 03:05

OP UPDATE: Note that in the latest version of Julia (v0.5), the idiomatic approach to answering this question is to just define mysquare(x::Number) =

2条回答
  •  隐瞒了意图╮
    2020-12-29 03:57

    As of Julia 0.6 (c. June 2017), the "dot syntax" provides an easy and idiomatic way to apply a function to a scalar or an array.

    You only need to provide the scalar version of the function, written in the normal way.

    function mysquare{x::Number)
        return(x^2)
    end
    

    Append a . to the function name (or preprend it to the operator) to call it on every element of an array:

    x = [1 2 3 4]
    x2 = mysquare(2)     # 4 
    xs = mysquare.(x)    # [1,4,9,16]
    xs = mysquare.(x*x') # [1 4 9 16; 4 16 36 64; 9 36 81 144; 16 64 144 256]
    y  = x .+ 1          # [2 3 4 5]
    

    Note that the dot-call will handle broadcasting, as in the last example.

    If you have multiple dot-calls in the same expression, they will be fused so that y = sqrt.(sin.(x)) makes a single pass/allocation, instead of creating a temporary expression containing sin(x) and forwarding it to the sqrt() function. (This is different from Matlab/Numpy/Octave/R, which don't make such a guarantee).

    The macro @. vectorizes everything on a line, so @. y=sqrt(sin(x)) is the same as y = sqrt.(sin.(x)). This is particularly handy with polynomials, where the repeated dots can be confusing...

提交回复
热议问题