Julia/Variables
from Julia体験してみた
Julia/Variables
Variables · The Julia Language
Juliaでは、変数variablesは値valueに紐付いた名前
=で束縛
reassignmentできるし、そのときに型が変わってもいい
code:val_reassign.jl
julia> x = 42
42
julia> x * 2
84
julia> x = 666
666
型宣言している場合はこの限りではなさそう
code:type.jl
julia> y::Int64 = 666
666
julia> y = "foo"
ERROR: MethodError: Cannot convert an object of type String to an object of type Int64
The function convert exists, but no method is defined for this combination of argument types.
Closest candidates are:
convert(::Type{T}, ::T) where T<:Number
@ Base number.jl:6
convert(::Type{T}, ::T) where T
@ Base Base.jl:126
convert(::Type{T}, ::Number) where T<:Number
@ Base number.jl:7
...
Stacktrace:
1 top-level scope
@ REPL48:1
case sensitiveに識別される
code:case.jl
julia> X = false
false
julia> x
666
Unicode可
code:uni.jl
julia> 📚 = "book"
"book"
julia> 📚
"book"
REPLなどでは\文字列・・・<TAB>することでUnicodeの補完を利用できる
e.g. \^2<TAB> => ²
便利
絵文字も補完できる(\:clap:<TAB>など)
?するとヘルプモードに入るので、そこから調べることができる
code:help.jl
help?> ²
"²" can be typed by \^2<tab>
使っていない変数はシャドウイングできる
使える文字種:
Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than 00A0; in particular, Unicode character categories Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols), and a few other letter-like characters (e.g. a subset of the Sm math symbols) are allowed. Subsequent characters may also include ! and digits (0-9 and other characters in categories Nd/No), as well as other Unicode code points: diacritics and other modifying marks (categories Mn/Mc/Me/Sk), some punctuation connectors (category Pc), primes, and a few other characters.
_の組み合わせのみで構成される変数名は書き込み専用で、読み出せない
ダミーに便利
代入もまた式なので値を返す
代入した値が返される
code:jl
julia> (x = 42) == 42
true
命名規約
変数はlowercaseにする
_で名前を区切ることができるが、読み難い場合に限る
型とモジュールはPascalCaseにする
関数とマクロはlowercaseであり、_は使わない
引数を破壊・変更する関数は末尾に!をつけて識別しなければならない