Julia 語言簡潔,並且快速。 Julia 的宏在編譯期間自動變換句法,會在編譯後消失痕跡。因此使用宏來進行類型檢測和代碼展開,不會增長運行時間的開銷,是縮減有效代碼的好東西。json
注:宏只能檢測語法層面的東西,不能檢測計算後的數據類型,也就是隻能檢測編譯期可以確數組
定的東西,例如 is_str(x), is_int(x), is_rstr(x).數據結構
macro assert(ex, msgs...) msg_body = isempty(msgs) ? ex : msgs[1] msg = string(msg_body) return :($ex ? nothing : throw(AssertionError($msg))) end
Julia 的布爾值只有 true, false.函數
true == true ; false == false
將 Array 轉換成 Tuple:atom
my_tuple = ([1,2]...) x, y = my_tuple x == 1; y == 2
Dict 的使用:code
Dict 就是哈希,字典,是沒有順序的按照 key 索引的數據結構:索引
聲明一個字典:ip
dict = Dict()
這將聲明一個 Dict{Any,Any}
的字典。element
Julia 會根據輸入的數據來推斷字典的數據類型:字符串
dict = Dict("a" => 1, "b" => 2)
這將聲明一個 Dict{String,Int32}
的字典
若是不想讓 Julia 本身推斷,本身設置:
dict = Dict{String,Any}()
經常使用的字典函數:
獲取指定 key 的值:
if get(dict, "key", nothing) == nothing println("dict have not <key>") end
更新字典的值:
dict["b"] = 2
刪除字典的值:
delete!(dict, "a")
符號(Symbol), 符號是個好東西,由於它寫法夠簡單:
x = :symbol x == :symbol Symbol == typeof(x)
能夠用這種數據類型來作 Dict 的 key:
if key == :str println("it is str") end
Julia 沒有 switch/case 的條件判斷結構,但有一種替代方式,這種方式很醜:
function match_rule(rule) name, value = (rule...) name == :regex && return match_regex(value) name == :rules && return match_rules(value) name == :branch && return match_branch(value) name == :look && return match_look(value) return match_atom(rule) end
函數別名, 若是感受某個函數的名稱不夠順手,能夠改了:
const say println const len length const trim strip
若是函數定義很短,還有簡潔的定義方式:
read_file(x) = readstring(x) write_file(file, str) = write(file, str) import JSON to_json(x) = JSON.json(x) from_json(x) = JSON.parse(x) load_file(file) = JSON.parsefile(file)
數組函數中第一個參數是函數的函數:
julia> lst = [1,2,3,4] 4-element Array{Int32,1}: 1 2 3 4 julia> findfirst(isodd,lst) 1 julia> findlast(isodd,lst) 3 julia> find(isodd,lst) 2-element Array{Int32,1}: 1 3
嵌套數據結構定義:
type Atom name:String value::Union{String,Atom} pos::Int end
這樣就能夠聲明嵌套結構了:
atom = Atom("name", "value", 12) Atom("name", atom, 13)
在正則匹配函數 match 中,能夠設置 UInt32 格式的參數來設置 PCRE 支持的其餘模式:
## ANCHORED 0x80000000 julia> m = match(r"a . b"xms, "aa\nb", 1, 0x80000000) julia> m = match(r"a . b"xms, "aa\nb", 2, 0x80000000) RegexMatch("a\nb")
split String 的一個辦法:
julia> @b_str "abc" 3-element Array{UInt8,1}: 0x61 0x62 0x63
Julia 的類型系統會搗亂:
x = match(r"a", "ab") typeof(x.match) == SubString{String}
原本覺得返回的是 String, 但又出來一個新的類型,導致以前的類型判斷函數失效:
is_str(x) = typeof(x) == String
不過如今發現這個問題了,就好解決了:
typeof(String(x.match)) == String
@b_str 這個函數用在代碼中會出現莫名其妙的問題。 字符串 String, 若是按照 str[index] 索引的話,獲得的是 byte, 只有迭代 for .. in 才獲得 Char