Created
September 25, 2018 13:41
-
-
Save yuyosy/2a6eeffbf5f65b6f520de9686d4beee4 to your computer and use it in GitHub Desktop.
Julia <function>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 一般的な記法の関数定義 | |
function f1(a) | |
return a + 1 | |
end | |
println("f1 : ", f1(3)) | |
# 括弧をつけない関数f1は、関数オブジェクトとして、他の値と同じように受け渡しが可能 | |
g = f1 | |
println("g : ", g(3)) | |
# return文は省略可能 | |
# return文の省略をした場合、最後に行った演算や変数、数値、文字列などが返される | |
function f2(a, b) | |
a+=2 | |
b+=3 | |
a+b # a+bを返す | |
end | |
println("f2 : ", f2(1,1)) | |
# 以下のようなif-elseなどの条件分岐でも同様に省略ができる | |
# ただし、return文を付け、返り値であることを示したほうがよい | |
function f2_1(a,b) | |
if a == b | |
"同じ" | |
else | |
"違う" | |
end | |
end | |
println("f2_1 : ", f2_1(1, 1)) | |
# 関数に計算の式を代入(上と同様に最後に行った演算や変数、数値、文字列などが返される) | |
f3(a, b) = (a + b) / 2 | |
println("f3 : ", f3(2, 4)) | |
# 計算結果を複数返す | |
function f4(a, b) | |
return1 = a + b | |
return2 = a - b | |
return1, return2 | |
end | |
c1, c2 = f4(10, 2) | |
println("f4 : c1 = $c1 c2 = $c2") | |
# 多重ディスパッチ | |
# 引数の値の型によって実装の異なる関数 | |
function f5(a::Int) | |
println(" a[Int] = $a") | |
end | |
function f5(a::Float64) | |
println(" a[Float64] = $a") | |
end | |
function f5(a::Int, b::Int) | |
println(" a[Int] = $a, b[Int] = $b") | |
end | |
function f5(a, b) | |
println(" a = $a, b = $b") | |
end | |
println("f5 : ") | |
f5(2) # a[Int] = 2 | |
f5(2.0) # a[Float64] = 2.0 | |
f5(2, 3) # a[Int] = 2, b[Int] = 3 | |
f5(2, 2.0) # a = 2, b = 2.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment