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