LoginSignup
4
1

More than 3 years have passed since last update.

Julia関数のデフォルト引数

Posted at

Juliaの関数は引数を省略したときのデフォルト値を指定できる。

julia> function f(a, b=0)
           print("$a $b")
       end
f (generic function with 2 methods)

julia> f(1, 2)
1 2
julia> f(1)
1 0

まあ、これはこの手の言語としてはわりに普通の機能だ。でも、Juliaの場合、ちょっと面白いことに、このデフォルト値の部分に他の引数を参照した式がかける。

julia> function g(a::Vector{Int64}, b=length(a))
           print("$a $b")
       end
g (generic function with 2 methods)

julia> g([1,2,3])
[1, 2, 3] 3
julia> g([1,2,3], 10)
[1, 2, 3] 10

これは地味に便利。

ちなみにPythonでは書けない。

In [1]: def g(a, b=len(a)):
   ...:     print(a, b)
   ...:     
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-e17b8e13041f> in <module>()
----> 1 def g(a, b=len(a)):
      2     print(a, b)
      3 

NameError: name 'a' is not defined

こんな感じでエラーがでる。外部変数を参照して宣言することはできるが、宣言の際に評価されるだけなので挙動は全然違う

In [5]: x = [1,2]

In [6]: def g(a, b=len(x)):
   ...:     print(a,b)
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1