Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
language.md 3.45 KiB

$OTHERLANG to Julia
in 15 minutes

Always remember

  • you can Tab through almost anything in REPL
  • functions have useful help with examples, try ?cat
  • typeof(something) may give good info

Everything has a type that determines storage and value handling

  • Vector{Int}
[1, 2, 5, 10]
  • Matrix{Float64}
[1.0 2.0; 2.0 1.0]
  • Tuple
(1, 2.0, "SomeLabel") 
  • Set{Int}
  • Dict{Int,String}

Basic functionality and expectable stuff

Most concepts from C, Python and MATLAB are portable as they are.

Surprising parts:

  • arrays are indexed from 1 (for a relatively good reason)
    • Arrays: array[1], array[2:5], array[begin+1:end-1], size, length, cat, vcat, hcat, ...
  • code blocks begin and end with keywords
    • you can stuff everything on one line!
  • all functions can (and should) be overloaded
    • simply add a type annotation to parameter with :: to distinguish between implementations for different types
    • overloading is cheap
    • specialization to known simple types types is precisely the reason why compiled code can be fast
    • adding type annotations to code and parameters helps the compiler to do the right thing

Structured cycles

Using functional-style loops is much less error-prone to indexing errors.

  • Transform an array, original:
for i=eachindex(arr)
   arr[i] = sqrt(arr[i])
end

Structured:

map(sqrt, [1,2,3,4,5])
map((x,y) -> (x^2 - exp(y)), [1,2,3], [-1,0,1])
  • Summarize an array:
reduce(+, [1,2,3,4,5])
reduce((a,b) -> "$b $a", ["Use", "the Force", "Luke"])
reduce(*, [1 2 3; 4 5 6], dims=1)

Tricky question (): What is the overhead of the "nice" loops?

Array-creating loops and generators

julia> [i*10 + j for i = 1:3, j = 1:5]
3×5 Matrix{Int64}:
11   12   13   14   15
21   22   23   24   25
31   32   33   34   35

julia> join(sort([c for word in ["the result is 123", "what's happening?", "stuff"]
                    for c in word
                    if isletter(c)]))
"aaeeeffghhhiilnnpprssssttttuuw"

julia> Dict('a'+i => i for i=1:26)
Dict{Char, Int64} with 26 entries:
  'n' => 13
  'f' => 5
      ...

Control flow: subroutines (functions)

  • Multi-line function definition
function combine(a,b)
  return a + b
end
  • "Mathematical" neater definition