前回に引き続きJuliaについてです。
ドキュメントに沿って試していきます。
Functions
julia> function f(x,y)
x+y
end
f (generic function with 1 method)
julia> f(1,2)
3
julia> f(x,y) = x + y
f (generic function with 1 method)
julia> f(2,3)
5
- function使わなくてもf=で関数定義できるんですね。数式みたいです。
julia> g(x,y)::Int8 = x * y
g (generic function with 1 method)
julia> g(1,2)
2
julia> g(1.2,2.2)
ERROR: InexactError: Int8(Int8, 2.64)
Stacktrace:
[1] Type at ./float.jl:679 [inlined]
[2] convert at ./number.jl:7 [inlined]
[3] g(::Float64, ::Float64) at ./REPL[15]:1
[4] top-level scope at none:0
julia> typeof(g(1,2))
Int8
- 戻り値を指定することもできます。
Tuples と Named Tuples
julia> a = (1,2)
(1, 2)
julia> b= (1.0,"Hello" ,x->2x)
(1.0, "Hello", getfield(Main, Symbol("##19#20"))())
julia> b[3](2)
4
- 関数まで定義できちゃいましたw
julia> c = (name="John",age=30)
(name = "John", age = 30)
julia> c.name
"John"
julia> c.age
30
- 名前付きタプルもOKです。
Multiple Return Values
julia> multi(a,b) = (a+b,a*b)
multi (generic function with 1 method)
julia> multi(1,2)
(3, 2)
julia> a , b = multi(1,2)
(3, 2)
julia> a
3
julia> b
2
戻り値が複数でもOKですね。
Varargs Functions(可変引数)
julia> bar(a,b,x...) = (a,b,x)
bar (generic function with 1 method)
julia> bar(1,2)
(1, 2, ())
julia> bar(1,2,3)
(1, 2, (3,))
julia> bar(1,2,3,4)
(1, 2, (3, 4))
julia> bar(1,2,"a")
(1, 2, ("a",))
julia> bar(1,2,"a",1)
(1, 2, ("a", 1))
...を使うと可変引数が使えます。
Optional Arguments
julia> opt(x,y=2,z=3) = x * y * z
opt (generic function with 3 methods)
julia> opt(1)
6
julia> opt(1,3)
9
julia> opt(1,3,-1)
-3
無指定の場合の値が設定できます。
Keyword Arguments
julia> plot(x,y;width=1,color="black") = "$x , $y , $width , $color"
plot (generic function with 1 method)
julia> plot(1,2)
"1 , 2 , 1 , black"
julia> plot(1,2,color="red")
"1 , 2 , 1 , red"
julia> plot(1,2,width=100)
"1 , 2 , 100 , black"```
セミコロンで区切るとキーワード付きにできます。
ドットを使うとベクトルに対しての処理ができるようですがまだ使わないのでスキップ、ちなみにこんな感じだそうです。
julia> [1,2,3] .*2
3-element Array{Int64,1}:
2
4
6
julia> sin. ([1,2,3])
3-element Array{Float64,1}:
0.8414709848078965
0.9092974268256817
0.1411200080598672
今日はこの辺で。