経緯
講義でliterals
とvalues
の区別について教わったので備忘録として。stackoverflowの説明が分かりやすかったのでこちらを参考にしてみる。実際の質問はここ(ひとつ上のクラス)を参考に回答しているので要所要所掻い摘んで。
目次
-
literal
とvalue
- それぞれの違い
literal
とvalue
wikiによるとコンピューターサイエンスにおけるliteral
とは
a notation for representing a value within programming language source code
ザックリ言うとassignment statement
(i.g. x = 1)において=
の右にくるもの(勿論全てではない)。
stackoverflowで見つけた例は以下のとおり:
Examples:
"hey" (a string)
false (a boolean)
3.14 (a real number)
[1,2,3] (a list of numbers)
(x) => x*x (a function)
/^1?$|^(11+?)\1+$/ (a regexp)
Some things that are not literals:
std::cout (an identifier)
foo = 0; (a statement)
1+2 (an expression)
別のstackoverflowでの解答では
a literal is kind of container, so it'll be better to compare between values and containers.
literals
を入れ物として考えたほうが分かりやすいと。
例えばint x = 1
という式において、一般的にx
はcontainer
、1
はvalue
として扱われるが、厳密には1
にもvalue
に加えてcontainer
としての要素が含まれている。その要素をliteral
と呼ぶ。つまり1
にはvalue
としての1
とliteral
としての1
がある。int x = 1
というコードを書く上で、1
というliteral
を書くことによって我々が1
のvalue
を示している。value
には直接アクセスできないのでliteral
というcontainer
を介して1
というvalue
にアクセスしていると考えても良い。
よって以下の引用が成り立つ:
A literal is a container that can be translated directly to a value without looking at it's surrounding - for example 1 can be translated directly to the number one. x can not be translated to a value in such a way, since it's a variable and we don't know what it holds unless we look at the surrounding code.
一応wikiによるvalue
の定義:
In computer science, a value is an expression which cannot be evaluated any further (a normal form).[1] The members of a type are the values of that type.[2] For example, the expression 1 + 2 is not a value as it can be reduced to the expression 3. This expression cannot be reduced any further (and is a member of the type Nat) and therefore is a value.
それぞれの違い
講義によるそれぞれの違いの定義付けは
言語によっても定義が変わってくるので一般的な解釈はこれくらいで。