上面例子中定义了一个匿名函数,即lambda,然后函数!作为参数传递。lambda还可以arg -> expr_body进行定义:
julia> lambda = val ->( "$val" * "$val","$val","...") #317 (generic function with 1 method) julia> lambda("wow") ("wowwow", "wow", "...")注意lambda函数体的()表示tuple,它可以让函数返回多个值。
Julia支持指定参数类型,默认值以及关键字形参
julia> misc = function(a::Int,b::Int=2;flag=true) a+1,b+2,!flag end #341 (generic function with 2 methods) julia> misc(1,2,flag=false) (2, 4, true)这个小标题是函数和方法,那么方法呢?其实在其他很多语言中,方法是面向对象领域的函数的别称。这里Julia给了另一种定义:
It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding two floating-point numbers, both of which are distinct from adding an integer to a floating-point number. Despite their implementation differences, these operations all fall under the general concept of "addition". Accordingly, in Julia, these behaviors all belong to a single object: the + function. To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a function is called a method.
方法是函数更具体的表现形式。如果学过C++那完全可以类比,函数就是模板函数,方法就是特化的函数模板。
控制流Julia的控制流和其他高级语言基本类似,这里就直接给例子了。
复合表达式
julia> z = begin a=1 b=2 (a+b,a/b) end julia> z (3, 0.5)条件运算
#julia也提供 ?: 三元运算符 if flag && a<b println("a <b") elseif flag && a==b println("a==b") elseif flag && a<b println("a>b") endwhile循环
julia> let i=0,res=0 while i<=100 res +=i i+=1 end println(res) end 5050for循环
julia> for i=1:10 print(i," ") end 1 2 3 4 5 6 7 8 9 10 julia> for name in ["Alice","Andrew","Jane"] print(name*" ") end Alice Andrew Jane julia> while true println(i) global i+=1 if i<5 continue else break end end 5异常处理
julia> throw("exception") ERROR: "exception" Stacktrace: [1] top-level scope at none:0 ... julia> try sqrt(-1) catch y println(y) end DomainError(-1.0, "sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).")关于Julia的Task后面我可能会再写一篇文章详细说说。
作用域模块是现代软件开发必不可少的成分,Julia也提供了对它的支持。使用module end即可创建一个模块,import进行导入:
julia> module warehouse x = 1 y = (arg,val) -> arg(arg(val)) end WARNING: replacing module warehouse. Main.warehouse julia> import .warehouse julia> warehouse.y(+,2) 2 复合类型使用struct ... end进行可以创建一个复合类型,这就是Julia提供的面向对象的方法
struct Novel name::String author::String price::Float64 # 构造函数 Novel(name::String,author::String,price::Float64) = new(name,author,price) end function stringify(val::Novel) print("Novel{",val.name,",",val.author,",",val.price,"}") end ff = Novel("Gobacktoearth","yy",56.4) stringify(ff) Novel{Gobacktoearth,yy,56.4}