Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@hidemotoNakada

Julia関数のデフォルト引数

More than 1 year has passed since last update.

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)
1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?