UP | HOME

Julia

Table of Contents

1 Julia Lang

1.1 Macros

Julia macros are hygienic:

First, variables within a macro result are classified as either local or global. A variable is considered local if it is assigned to (and not declared global), declared local, or used as a function argument name. Otherwise, it is considered global.

Local variables are then renamed to be unique (using the gensym function, which generates new symbols), and global variables are resolved within the macro definition environment.

And you can escape the hygienic by esc, e.g.

macro zerox()
    return esc(:(x = 0))
end

A common pattern:

for op = (:sin, :cos, :tan, :log, :exp)
    eval(:(Base.$op(a::MyNumber) = MyNumber($op(a.x))))
end

2 Standard library

2.1 string

interpolation:

var = 5
"$var-$(now())"

concatenation:

"hello" * "world"
findfirst(isequal('c'), "abcdc")
findnext(isequal('c'), "abcdc", 3)
occursin("world", "hello world")

regular expression:

occursin(r"^\s*(?:#|$)", "# a comment")
m = match(r"(a|b)(c)?(d)", "acd")
m.match
m.captures
m.offset
m.offsets

replace("a", r"." => s"\g<0>1")
# => "a1"

parse:

parse("123", Int)

2.2 I/O

IO descriptors

  • Base.stdout
  • Base.stderr
  • Base.stdin

Open file:

open("myfile.txt", "w") do io
    write(io, "Hello world!")
end

Read and write:

  • write(io, x)
  • flush(io)
  • read(io, String): read all content
  • read(io, Char): read a char
  • readline(io)
  • readlines(io)
    • eachline(io): similar to readlines, but this is iterable
  • readuntil(io, delim)

seek and position:

  • position(io): return the current position
  • seek(io, pos): seek to pos

To test IO functions, use io=IOBuffer("hello world")

2.3 FS

In Base.Filesystem

walking dir:

readdir("/path/to/dir")
# => array of filenames and dirnames

for (root, dirs, files) in walkdir(".")
    println("Directories in $root")
    for dir in dirs
        println(joinpath(root, dir)) # path to directories
    end
    println("Files in $root")
    for file in files
        println(joinpath(root, file)) # path to files
    end
end

isdir(path)
isfile(path)

Modifying:

mkdir("/path/to/dir")
mkpath("/this/is/mkdir/-p/")
cp(src, dst)
mv(src, dst)
rm(path)
touch(path)
chmod()
chown()

Tempdir

mktemp()
# => (path, io), this is temp file

mktempdir()
# => path

pathname:

dirname(path)
basename(path)
joinpath(parts...)
splitpath(path)
# remove . and ..
normpath(path)
expanduser(path)

2.4 random numbers

basic:

rand()
# N(0,1)
randn()
randstring('a':'z', len=8)
randperm()
shuffle()
seed!(1234)

use a custom generator:

using Distributions
dist = MvNormal(11, 1)
rand(dist, 100)

2.5 network

download(url, localfile)

2.6 Useful functions

  • sortperm(v): Return a permutation vector I that puts v[I] in sorted order.
  • findfirst(predicate::Function, A): Return the index or key of the first element of A for which predicate returns true.
  • mapreduce(f, op, itrs...; [init]): Apply function f to each element(s) in itrs, and then reduce the result using the binary function op

intuitive ones:

  • reverse
  • abs
  • median

3 Tools

3.1 profiling

Profile.init(n = 10^7, delay = 0.01)
Profile.clear()

@profile foo()

Profile.print()

3.2 Using Pkg

using Pkg
Pkg.add(PackageSpec(url="https://github.com/lihebi/julia-repl", rev="master"))

To develop a project:

Pkg.develop(PackageSpec(url="https://github.com/lihebi/julia-repl"))

Then view the current pkg status:

Pkg.status()

You will see:

EmacsREPL v0.1.0 [`~/.julia/dev/EmacsREPL`]

4 Third-party Libraries

4.3 ML library

4.4 Optimizers

4.7 Datasets

4.8 Images

colorview, channelview, RGB

4.9 Graph

4.9.1 LightGraphs.jl

A great package for

  • just the graph
  • generate different random graphs
  • traversal
  • plotting
  • algorithms:
    • shortest path
    • minimum spanning tree
  • distance metrics

4.9.2 MetaGraphs.jl

LightGraphs with arbitrary data on nodes.

4.9.3 Compose.jl

The racket/pict for Julia.

4.10 Compiler tools

4.11 Probablistic packages