経緯
講義で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.
それぞれの違い
講義によるそれぞれの違いの定義付けは
言語によっても定義が変わってくるので一般的な解釈はこれくらいで。
