text:
# Generated by the singletons

1. Oct 7, 2013

### shoeburg

Hello,

I just started a prob theory class and i'm a total beginner. I can't find the definition of the following anywhere:
1) What does it mean for a set to be generated by the singletons? In other words, how do I show a certain set is generated by the singletons
2) Similarly, what does it mean to be generated by a collection of sets?

My guess: A set generated by the singletons (or a collection of sets) means that that set can be formed by taking all the singletons and unioning them and complementing them, which leads us to a borel field?

2. Oct 7, 2013

### jbunniii

It is meaningless to say that a SET is generated by singletons. But one can start with a set, say $X$, and a collection $B$ of subsets of $X$, and consider the algebra (aka field) generated by $B$. This is simply the smallest algebra that can be defined on $X$ which includes all of the subsets in $B$. Equivalently, it is the intersection of all algebras on $X$ which contain $B$.

In your case, you have some set $X$ and can define $B$ to be the set of all singletons in $X$. Then there is some smallest algebra which contains all the singletons, namely the intersection of all algebras that contain all the singletons.

3. Oct 8, 2013

### shoeburg

Okay. I'm slowly picking up on this. Specifically, I'm asked to prove: Let B be the collection of all subsets of A (a sigma-algebra?). A is countable if and only if B is generated by the singletons. See my only experience with generators is from a couple abstract algebra courses I've taken, so in my head I'm thinking of a bunch of singletons doing some operation amongst themselves like unioning until all possibilities are exhausted. I'm not sure what exactly I'm trying to prove to show its generated by said singletons. I appreciate your help.

4. Oct 8, 2013

### jbunniii

That's more or less correct, but it's not the only characterization, and sometimes other, equivalent statements are easier to work with:

(1) the sigma algebra $Y$ is generated by the singletons

if and only if

(2) $Y$ is the smallest sigma algebra on $A$ which contains all the singletons

if and only if

(3) $Y$ is the intersection of all sigma algebras on $A$ which contain the singletons

if and only if

(4) if $Z$ is any sigma algebra on $X$ which contains all the singletons, then $Y \subset Z$

Keeping this in mind, let's look at your problem. You have $B = \mathcal{P}(A) =$ the power set of $A$.

Suppose that $A$ is countable. Suppose that $Z$ is a sigma algebra containing all the singletons of $A$. Since $Z$ is closed under countable unions, and $A$ is countable, it follows that every subset of $A$ is in $Z$. Thus, $B = \mathcal{P}(A) \subset Z$. Therefore $B$ satisfies the role of $Y$ in (4) above. Since (4) is equivalent to (1), it follows that $B$ is generated by the singletons.

See if you can find a similar argument for the reverse implication.

5. Oct 10, 2013

### shoeburg

Okay. Let B be generated by the singletons. Since B is a sigma-algebra, it is closed under countable unions, and since it must contain every singleton, there must then only be a countable number of singletons, implying A is countable.

6. Oct 11, 2013

### jbunniii

I don't see where you used the fact that B is generated by the singletons.

The power set of $\mathbb{R}$ (i.e. the set of all subsets of the real numbers) is a sigma algebra, and it contains all the singletons, but there are an uncountable number of singletons.

7. Oct 11, 2013

### jbunniii

Suppose the sigma algebra $B = \mathcal{P}(A)$, the power set of $A$, is generated by the singletons of $A$.

Consider the set $C = \{S \subset A : \text{ either }S \text{ is countable or }S^c\text{ is countable}\}$.

Claim 1: $C$ is a sigma algebra
Claim 2: $B \subset C$

Can you prove these claims? Can you use them to prove that $A$ must be countable?

8. Oct 11, 2013

### shoeburg

Whoops. Does it make sense to say that since B is the smallest sigma-algebra on A containing the singletons, then it is at most countable, because if it was uncountable it couldn't be the smallest?

9. Oct 11, 2013

### shoeburg

Whoops again I didn't see your second post. I'll try that. I really appreciate your help.

10. Oct 11, 2013

### jbunniii

FYI, I made a correction to my last post - please refresh to make sure you get the corrected version.

11. Oct 11, 2013

### jbunniii

But your goal is to show that $A$ is countable, not $B$. Indeed, if $A$ is countably infinite and $B$ is the power set of $A$, then $B$ is always uncountable.


text:
# What are the higher homotopy groups of Spec Z ?

The homotopy groups of the étale topos of a scheme were defined by Artin and Mazur. Are these known for Spec Z? Certainly π1 is trivial because Spec Z has no unramified étale covers, but what is known about the higher homotopy groups?

-

Since nobody else is answering this question I will give a few vague thoughts. Caveat: this is a completely speculative answer for various reasons, not least of which because I don't know Artin-Mazur's definition of pi_i.

Since X = Spec(Z) is "simply connected", one can pretend that the Hurewicz theorem applies.

I believe that H^i(X,Z/nZ) is trivial for all i, as a consequence of class field theory and the fact that Z has neither many units nor n-th roots of unity. (I'm not completely sure about i = 3 and n = 2 here.) One can then squint and imagine that the higher homotopy groups of X are trivial. This seems a little dodgy. Another direction one could go is to note that the groups H^i(X,G_m) vanish unless i = 3, and H^3(X,G_m) = Q/Z. From this (and other) facts it has been argued that X is analogous to the 3-sphere.

For what it is worth, both computations suggest that pi_2(X) is trivial. If one wanted to turn this comment into mathematics, one should try to define an algebraic Hurewicz map.

-
Indeed H^i(X) is supposed to point out that X looks like a 3-sphere and it's not like homotopy groups of S^3 are easy. –  Ilya Nikokoshev Nov 3 '09 at 9:03
My memory is vague, but does H^3(X,G_m) = Q/Z imply that there are nontrivial elements in H^3(X,Z/2) arising from the kernel of the squaring map G_m -> G_m, since Z/2 and the 2nd roots of unity represent the same etale sheaf on this site? –  Tyler Lawson Nov 3 '09 at 12:23
\mu_2 is not etale over Spec(Z). –  moonface Nov 3 '09 at 13:52
The word "represent" may not have been the best to use. No, it's not etale, but it's a sheaf on the etale site as the kernel of the map G_m -> G_m. (The cokernel, if I remember correctly, is isomorphic the direct image of the additive group on the etale site of Z/2.) –  Tyler Lawson Nov 3 '09 at 15:02
Oh, I see what you mean. Thanks for clarifying! –  moonface Nov 3 '09 at 17:20

If etale pi_1 classifies obstructions to trivializing finite flat unramified Z-algebras, it would be nice if the whole etale homotopy type classified obstructions to trivializing simplicial commutative Z-algebras that were finite, flat, and unramified in a homotopy sense. I think all of these notions make sense: "finite" means that the homotopy groups vanish in high degrees and are finitely generated, "flat" means that these homotopy groups have no torsion, and "unramified" means that the cotangent complex is zero. Is that right?

Presumably algebraic topologists have thought about the sphere spectrum version of this question. Are there any connective E-infinity ring spectra that are finite, flat, and unramified over the sphere?

After Tyler's comments, I see that this is a bad analogy. The dictionary between etale locally constant sheaves of sets and finite flat unramified algebras (which in one direction takes an algebra and associates the sheaf of sections of its spectrum over Spec Z) just doesn't extend to a dictionary between homotopy-style locally constant sheaves and homotopy-style finite flat unramified algebras.

-
With regards to your second question: This appears in John Rognes' paper on Galois theory of structured ring spectra, at least in part. There are none if you ask that the generators all live in pi_0. If you allow new generators in positive degrees, there are square-zero extensions and their ilk, and more following those that are harder to classify. I am not sure about your first question. –  Tyler Lawson Nov 3 '09 at 21:52
Are you really saying that there are square-zero extensions of the sphere spectrum that are unramified? This isn't possible with plain rings. –  David Treumann Nov 3 '09 at 22:55
I guess I was thinking by analogy with your "homotopy vanishing in high degrees" examples above. No, those can't ever have trivial cotangent complex, and thickenings of a commutative Z-algebra to something with positive homotopy groups usually can't either; e.g. if R -> S is an isomorphism on pi_0 then the first nonvanishing relative homotopy group coincides with the first nonzero homotopy group of the cotangent complex. –  Tyler Lawson Nov 4 '09 at 0:35

format: plain


text:
Is there a way to develop a multiple controlled X or Z gate on Qiskit without using ancillary qubits?

I know for instance I can derive a cccX gate using 2 Toffoli gates on 5 qubit wire or ccccX with 3 Toffoli gates and 7 qubits and so on. you will notice the depth is increasing as the number of control qubits increase, that is for every additional c, there are 2 additional qubits. Is there a better way I can derive these multiple controlled x gate using fewer resources (gates and qubits)?

This Qiskit tutorial does what I think you're looking for; with the cnx() function. It uses this paper to decompose the CNOT gate without ancilla qubits.
• Replaced the depreciated cu3 gates with cu gates and it worked perfectly. Thanks. – Chirag Kalra Feb 27 at 10:42


text:
MathSciNet bibliographic data MR1269937 (95f:28013) 28A80 Hu, Xiaoyu; Taylor, S. James Fractal properties of products and projections of measures in ${\bf R}\sp d$${\bf R}\sp d$. Math. Proc. Cambridge Philos. Soc. 115 (1994), no. 3, 527–544. Article

For users without a MathSciNet license , Relay Station allows linking from MR numbers in online mathematical literature directly to electronic journals and original articles. Subscribers receive the added value of full MathSciNet reviews.


text:
Posted on Categories:Non-Euclidean Geometry, 数学代写, 非欧几何

数学代写非欧几何代写Non-Euclidean Geometry代考|MATH353 The Rotation Proof

avatest™

avatest™帮您通过考试

avatest™的各个学科专家已帮了学生顺利通过达上千场考试。我们保证您快速准时完成各时长和类型的考试，包括in class、take home、online、proctor。写手整理各样的资源来或按照您学校的资料教您，创造模拟试题，提供所有的问题例子，以保证您在真实考试中取得的通过率是85%以上。如果您有即将到来的每周、季考、期中或期末考试，我们都能帮助您！

•最快12小时交付

•200+ 英语母语导师

•70分以下全额退款

数学代写非欧几何代写Non-Euclidean Geometry代考|The Rotation Proof

This ostensible proof, due to Bernhard Friedrich Thibaut ${ }^{14}$ $\left(1775^{-1} 832\right)$ is worthy of note because it has from time to time appeared in elementary texts and has otherwise been indorsed. The substance of the proof is as follows:

In triangle $A B C$ (Fig. i 8 ), allow side $A B$ to rotate ahout $A$, clock- wise, until it coincides with $C A$ produced to $L$. Let $C L$ rotate clockwise about $C$ until it coincides with $B C$ produced to $M$. Finally, when $B M$ has been rotated clockwise about $B$, untıl it coincides with $A B$ produced to $N$, it appears that $A B$ has undergone a complete rotation through four right angles. But the three angles of rotation are the three exterior angles of the triangle, and since their sum is equal to four right angles, the sum of the interior angles must be equal to two right angles.This proof is typical of those which depend upon the idea of direction. The circumspect reader will observe that the rotations take place about different points on the rotating line, so that not only rotation, but translation, is involved. In fact, one sees that the segment $A B$, after the rotations described, has finally been translated along $A B$ through a distance equal to the perımeter of the triangle. Thus it is assumed in the proof that the translations and rotations are independent, and that the translations may be ignored. But this is only truc in Euclidean Geometry and its assumption amounts to taking for granted the Fifth Postulate. The very same argument can be used for a spherical triangle, with the same conclusion, although the sum of the angles of any such trıangle is always greater than two right angles.

数学代写非欧几何代写Non-Euclidean Geometry代考|Comparison of Infinite Areas

Another proof, which has from time to time captured the favor of the unwary, is due to the Swiss mathematician, Louis Bertrand ${ }^{16}$
${ }^{16}$ See his correspondence with Schumacher, Engel and Stackel, loc ctt, pp. 227-230.
${ }^{16}$ Développement nouveau de la partie élémentaire des Mathématiques, Vol. II,
p. 19 (Geneva, 1778 )

$(1731-1812)$. He attempted to prove the Fifth Postulate directly, using in essence the following argument:

Given two lines $A P_1$ and $A_1 B_1$ (Fig. 19) cut by the transversal $A A_1$ in such a way that the sum of angles $P_1 A A_1$ and $A A_1 B_1$ is less than two right angles, it is to be proved that $A P_1$ and $A_1 B_1$ meet if sufficiently produced.

Construct $A B$ so that angle $B A A_1$ is equal to angle $B_1 A_1 A_2$, where $A_2$ is a point on $A A_1$ produced through $A_1$. Then $A P_1$ will lie within angle $B A A_1$, since angle $P_1 A A_1$ is less than angle $B_1 A_1 A_2$. Construct $A P_2, A P_3, \ldots, A P_n$ so that angles $P_1 A P_2, P_2 A P_3, \ldots, P_{n-1} A P_n$ are all equal to angle $B A P_1$. Since an integral multiple of angle $B A P_1$ can be found which exceeds angle $B A A_1, n$ can be chosen so large that $A P_n$ will fall below $A A_1$ and angle $B A P_n$ be greater than angle $B A A_1$. Since the infinite sectors $B A P_1, P_1 A P_2, \ldots, P_{n-1} A P_n$ can be superposed, they have equal areas and each has an area equal to that of the infinite sector $B A P_n$ divided by $n$.

数学代写非欧几何代写Non-Euclidean Geometry代考|Comparison of InfiniteAreas

16 㕕见他与 Schumacher、Engel 和 Stackel 的通信， loc ctt，第 227-230页。
${ }^{16}$ 数学葚础部分的新发展，卷。二，

(1731-1812). 他试图直接证明第五公设, 本质上使用以下论证:

MATLAB代写

MATLAB 是一种用于技术计算的高性能语言。它将计算、可视化和编程集成在一个易于使用的环境中，其中问题和解决方案以熟悉的数学符号表示。典型用途包括：数学和计算算法开发建模、仿真和原型制作数据分析、探索和可视化科学和工程图形应用程序开发，包括图形用户界面构建MATLAB 是一个交互式系统，其基本数据元素是一个不需要维度的数组。这使您可以解决许多技术计算问题，尤其是那些具有矩阵和向量公式的问题，而只需用 C 或 Fortran 等标量非交互式语言编写程序所需的时间的一小部分。MATLAB 名称代表矩阵实验室。MATLAB 最初的编写目的是提供对由 LINPACK 和 EISPACK 项目开发的矩阵软件的轻松访问，这两个项目共同代表了矩阵计算软件的最新技术。MATLAB 经过多年的发展，得到了许多用户的投入。在大学环境中，它是数学、工程和科学入门和高级课程的标准教学工具。在工业领域，MATLAB 是高效研究、开发和分析的首选工具。MATLAB 具有一系列称为工具箱的特定于应用程序的解决方案。对于大多数 MATLAB 用户来说非常重要，工具箱允许您学习应用专业技术。工具箱是 MATLAB 函数（M 文件）的综合集合，可扩展 MATLAB 环境以解决特定类别的问题。可用工具箱的领域包括信号处理、控制系统、神经网络、模糊逻辑、小波、仿真等。


text:
## File: 05-classes-and-objects.md

package info (click to toggle)
scala 2.11.12-5
 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149 --- title: Classes & Objects layout: default chapter: 5 --- # Classes and Objects ebnf TmplDef ::= [case'] class' ClassDef | [case'] object' ObjectDef | trait' TraitDef  [Classes](#class-definitions) and [objects](#object-definitions) are both defined in terms of _templates_. ## Templates ebnf ClassTemplate ::= [EarlyDefs] ClassParents [TemplateBody] TraitTemplate ::= [EarlyDefs] TraitParents [TemplateBody] ClassParents ::= Constr {with' AnnotType} TraitParents ::= AnnotType {with' AnnotType} TemplateBody ::= [nl] {' [SelfType] TemplateStat {semi TemplateStat} }' SelfType ::= id [:' Type] =>' | this :' Type =>'  A template defines the type signature, behavior and initial state of a trait or class of objects or of a single object. Templates form part of instance creation expressions, class definitions, and object definitions. A template $sc$ with $mt_1$ with $\ldots$ with $mt_n$ { $\mathit{stats}$ } consists of a constructor invocation $sc$ which defines the template's _superclass_, trait references $mt_1 , \ldots , mt_n$ $(n \geq 0)$, which define the template's _traits_, and a statement sequence $\mathit{stats}$ which contains initialization code and additional member definitions for the template. Each trait reference $mt_i$ must denote a [trait](#traits). By contrast, the superclass constructor $sc$ normally refers to a class which is not a trait. It is possible to write a list of parents that starts with a trait reference, e.g. $mt_1$ with $\ldots$ with $mt_n$. In that case the list of parents is implicitly extended to include the supertype of $mt_1$ as first parent type. The new supertype must have at least one constructor that does not take parameters. In the following, we will always assume that this implicit extension has been performed, so that the first parent class of a template is a regular superclass constructor, not a trait reference. The list of parents of a template must be well-formed. This means that the class denoted by the superclass constructor $sc$ must be a subclass of the superclasses of all the traits $mt_1 , \ldots , mt_n$. In other words, the non-trait classes inherited by a template form a chain in the inheritance hierarchy which starts with the template's superclass. The _least proper supertype_ of a template is the class type or [compound type](03-types.html#compound-types) consisting of all its parent class types. The statement sequence $\mathit{stats}$ contains member definitions that define new members or overwrite members in the parent classes. If the template forms part of an abstract class or trait definition, the statement part $\mathit{stats}$ may also contain declarations of abstract members. If the template forms part of a concrete class definition, $\mathit{stats}$ may still contain declarations of abstract type members, but not of abstract term members. Furthermore, $\mathit{stats}$ may in any case also contain expressions; these are executed in the order they are given as part of the initialization of a template. The sequence of template statements may be prefixed with a formal parameter definition and an arrow, e.g. $x$ =>, or $x$:$T$ =>. If a formal parameter is given, it can be used as an alias for the reference this throughout the body of the template. If the formal parameter comes with a type $T$, this definition affects the _self type_ $S$ of the underlying class or object as follows: Let $C$ be the type of the class or trait or object defining the template. If a type $T$ is given for the formal self parameter, $S$ is the greatest lower bound of $T$ and $C$. If no type $T$ is given, $S$ is just $C$. Inside the template, the type of this is assumed to be $S$. The self type of a class or object must conform to the self types of all classes which are inherited by the template $t$. A second form of self type annotation reads just this: $S$ =>. It prescribes the type $S$ for this without introducing an alias name for it. ###### Example Consider the following class definitions: scala class Base extends Object {} trait Mixin extends Base {} object O extends Mixin {}  In this case, the definition of O is expanded to: scala object O extends Base with Mixin {}  **Inheriting from Java Types** A template may have a Java class as its superclass and Java interfaces as its mixins. **Template Evaluation** Consider a template $sc$ with $mt_1$ with $mt_n$ { $\mathit{stats}$ }. If this is the template of a [trait](#traits) then its _mixin-evaluation_ consists of an evaluation of the statement sequence $\mathit{stats}$. If this is not a template of a trait, then its _evaluation_ consists of the following steps. - First, the superclass constructor $sc$ is [evaluated](#constructor-invocations). - Then, all base classes in the template's [linearization](#class-linearization) up to the template's superclass denoted by $sc$ are mixin-evaluated. Mixin-evaluation happens in reverse order of occurrence in the linearization. - Finally the statement sequence $\mathit{stats}\,$ is evaluated. ###### Delayed Initialization The initialization code of an object or class (but not a trait) that follows the superclass constructor invocation and the mixin-evaluation of the template's base classes is passed to a special hook, which is inaccessible from user code. Normally, that hook simply executes the code that is passed to it. But templates inheriting the scala.DelayedInit trait can override the hook by re-implementing the delayedInit method, which is defined as follows: scala def delayedInit(body: => Unit)  ### Constructor Invocations ebnf Constr ::= AnnotType {(' [Exprs] )'}  Constructor invocations define the type, members, and initial state of objects created by an instance creation expression, or of parts of an object's definition which are inherited by a class or object definition. A constructor invocation is a function application $x$.$c$[$\mathit{targs}$]($\mathit{args}_1$)$\ldots$($\mathit{args}_n$), where $x$ is a [stable identifier](03-types.html#paths), $c$ is a type name which either designates a class or defines an alias type for one, $\mathit{targs}$ is a type argument list, $\mathit{args}_1 , \ldots , \mathit{args}_n$ are argument lists, and there is a constructor of that class which is [applicable](06-expressions.html#function-applications) to the given arguments. If the constructor invocation uses named or default arguments, it is transformed into a block expression using the same transformation as described [here](sec:named-default). The prefix $x$. can be omitted. A type argument list can be given only if the class $c$ takes type parameters. Even then it can be omitted, in which case a type argument list is synthesized using [local type inference](06-expressions.html#local-type-inference). If no explicit arguments are given, an empty list () is implicitly supplied. An evaluation of a constructor invocation $x$.$c$[$\mathit{targs}$]($\mathit{args}_1$)$\ldots$($\mathit{args}_n$) consists of the following steps: - First, the prefix $x$ is evaluated. - Then, the arguments $\mathit{args}_1 , \ldots , \mathit{args}_n$ are evaluated from left to right. - Finally, the class being constructed is initialized by evaluating the template of the class referred to by $c$. ### Class Linearization The classes reachable through transitive closure of the direct inheritance relation from a class $C$ are called the _base classes_ of $C$. Because of mixins, the inheritance relationship on base classes forms in general a directed acyclic graph. A linearization of this graph is defined as follows. ###### Definition: linearization Let $C$ be a class with template $C_1$ with ... with $C_n$ { $\mathit{stats}$ }. The _linearization_ of $C$, $\mathcal{L}(C)$ is defined as follows: $$\mathcal{L}(C) = C, \mathcal{L}(C_n) \; \vec{+} \; \ldots \; \vec{+} \; \mathcal{L}(C_1)$$ Here $\vec{+}$ denotes concatenation where elements of the right operand replace identical elements of the left operand: $$\begin{array}{lcll} \{a, A\} \;\vec{+}\; B &=& a, (A \;\vec{+}\; B) &{\bf if} \; a \not\in B \\\\ &=& A \;\vec{+}\; B &{\bf if} \; a \in B \end{array}$$ ###### Example Consider the following class definitions. scala abstract class AbsIterator extends AnyRef { ... } trait RichIterator extends AbsIterator { ... } class StringIterator extends AbsIterator { ... } class Iter extends StringIterator with RichIterator { ... }  Then the linearization of class Iter is scala { Iter, RichIterator, StringIterator, AbsIterator, AnyRef, Any }  Note that the linearization of a class refines the inheritance relation: if $C$ is a subclass of $D$, then $C$ precedes $D$ in any linearization where both $C$ and $D$ occur. [Linearization](#definition:-linearization) also satisfies the property that a linearization of a class always contains the linearization of its direct superclass as a suffix. For instance, the linearization of StringIterator is scala { StringIterator, AbsIterator, AnyRef, Any }  which is a suffix of the linearization of its subclass Iter. The same is not true for the linearization of mixins. For instance, the linearization of RichIterator is scala { RichIterator, AbsIterator, AnyRef, Any }  which is not a suffix of the linearization of Iter. ### Class Members A class $C$ defined by a template $C_1$ with $\ldots$ with $C_n$ { $\mathit{stats}$ } can define members in its statement sequence $\mathit{stats}$ and can inherit members from all parent classes. Scala adopts Java and C\#'s conventions for static overloading of methods. It is thus possible that a class defines and/or inherits several methods with the same name. To decide whether a defined member of a class $C$ overrides a member of a parent class, or whether the two co-exist as overloaded variants in $C$, Scala uses the following definition of _matching_ on members: ###### Definition: matching A member definition $M$ _matches_ a member definition $M'$, if $M$ and $M'$ bind the same name, and one of following holds. 1. Neither $M$ nor $M'$ is a method definition. 2. $M$ and $M'$ define both monomorphic methods with equivalent argument types. 3. $M$ defines a parameterless method and $M'$ defines a method with an empty parameter list () or _vice versa_. 4. $M$ and $M'$ define both polymorphic methods with equal number of argument types $\overline T$, $\overline T'$ and equal numbers of type parameters $\overline t$, $\overline t'$, say, and $\overline T' = [\overline t'/\overline t]\overline T$. Member definitions fall into two categories: concrete and abstract. Members of class $C$ are either _directly defined_ (i.e. they appear in $C$'s statement sequence $\mathit{stats}$) or they are _inherited_. There are two rules that determine the set of members of a class, one for each category: A _concrete member_ of a class $C$ is any concrete definition $M$ in some class $C_i \in \mathcal{L}(C)$, except if there is a preceding class $C_j \in \mathcal{L}(C)$ where $j < i$ which directly defines a concrete member $M'$ matching $M$. An _abstract member_ of a class $C$ is any abstract definition $M$ in some class $C_i \in \mathcal{L}(C)$, except if $C$ contains already a concrete member $M'$ matching $M$, or if there is a preceding class $C_j \in \mathcal{L}(C)$ where $j < i$ which directly defines an abstract member $M'$ matching $M$. This definition also determines the [overriding](#overriding) relationships between matching members of a class $C$ and its parents. First, a concrete definition always overrides an abstract definition. Second, for definitions $M$ and $M$' which are both concrete or both abstract, $M$ overrides $M'$ if $M$ appears in a class that precedes (in the linearization of $C$) the class in which $M'$ is defined. It is an error if a template directly defines two matching members. It is also an error if a template contains two members (directly defined or inherited) with the same name and the same [erased type](03-types.html#type-erasure). Finally, a template is not allowed to contain two methods (directly defined or inherited) with the same name which both define default arguments. ###### Example Consider the trait definitions: scala trait A { def f: Int } trait B extends A { def f: Int = 1 ; def g: Int = 2 ; def h: Int = 3 } trait C extends A { override def f: Int = 4 ; def g: Int } trait D extends B with C { def h: Int }  Then trait D has a directly defined abstract member h. It inherits member f from trait C and member g from trait B. ### Overriding A member $M$ of class $C$ that [matches](#class-members) a non-private member $M'$ of a base class of $C$ is said to _override_ that member. In this case the binding of the overriding member $M$ must [subsume](03-types.html#conformance) the binding of the overridden member $M'$. Furthermore, the following restrictions on modifiers apply to $M$ and $M'$: - $M'$ must not be labeled final. - $M$ must not be [private](#modifiers). - If $M$ is labeled private[$C$] for some enclosing class or package $C$, then $M'$ must be labeled private[$C'$] for some class or package $C'$ where $C'$ equals $C$ or $C'$ is contained in $C$. - If $M$ is labeled protected, then $M'$ must also be labeled protected. - If $M'$ is not an abstract member, then $M$ must be labeled override. Furthermore, one of two possibilities must hold: - either $M$ is defined in a subclass of the class where is $M'$ is defined, - or both $M$ and $M'$ override a third member $M''$ which is defined in a base class of both the classes containing $M$ and $M'$ - If $M'$ is [incomplete](#modifiers) in $C$ then $M$ must be labeled abstract override. - If $M$ and $M'$ are both concrete value definitions, then either none of them is marked lazy or both must be marked lazy. A stable member can only be overridden by a stable member. For example, this is not allowed: scala class X { val stable = 1} class Y extends X { override var stable = 1 } // error  Another restriction applies to abstract type members: An abstract type member with a [volatile type](03-types.html#volatile-types) as its upper bound may not override an abstract type member which does not have a volatile upper bound. A special rule concerns parameterless methods. If a parameterless method defined as def $f$: $T$ = ... or def $f$ = ... overrides a method of type $()T'$ which has an empty parameter list, then $f$ is also assumed to have an empty parameter list. An overriding method inherits all default arguments from the definition in the superclass. By specifying default arguments in the overriding method it is possible to add new defaults (if the corresponding parameter in the superclass does not have a default) or to override the defaults of the superclass (otherwise). ###### Example Consider the definitions: scala trait Root { type T <: Root } trait A extends Root { type T <: A } trait B extends Root { type T <: B } trait C extends A with B  Then the class definition C is not well-formed because the binding of T in C is type T <: B, which fails to subsume the binding type T <: A of T in type A. The problem can be solved by adding an overriding definition of type T in class C: scala class C extends A with B { type T <: C }  ### Inheritance Closure Let $C$ be a class type. The _inheritance closure_ of $C$ is the smallest set $\mathscr{S}$ of types such that - $C$ is in $\mathscr{S}$. - If $T$ is in $\mathscr{S}$, then every type $T'$ which forms syntactically a part of $T$ is also in $\mathscr{S}$. - If $T$ is a class type in $\mathscr{S}$, then all [parents](#templates) of $T$ are also in $\mathscr{S}$. It is a static error if the inheritance closure of a class type consists of an infinite number of types. (This restriction is necessary to make subtyping decidable[^kennedy]). [^kennedy]: Kennedy, Pierce. [On Decidability of Nominal Subtyping with Variance.]( http://research.microsoft.com/pubs/64041/fool2007.pdf) in FOOL 2007 ### Early Definitions ebnf EarlyDefs ::= {' [EarlyDef {semi EarlyDef}] }' with' EarlyDef ::= {Annotation} {Modifier} PatVarDef  A template may start with an _early field definition_ clause, which serves to define certain field values before the supertype constructor is called. In a template scala { val $p_1$: $T_1$ = $e_1$ ... val $p_n$: $T_n$ = $e_n$ } with $sc$ with $mt_1$ with $mt_n$ { $\mathit{stats}$ }  The initial pattern definitions of $p_1 , \ldots , p_n$ are called _early definitions_. They define fields which form part of the template. Every early definition must define at least one variable. An early definition is type-checked and evaluated in the scope which is in effect just before the template being defined, augmented by any type parameters of the enclosing class and by any early definitions preceding the one being defined. In particular, any reference to this in the right-hand side of an early definition refers to the identity of this just outside the template. Consequently, it is impossible that an early definition refers to the object being constructed by the template, or refers to one of its fields and methods, except for any other preceding early definition in the same section. Furthermore, references to preceding early definitions always refer to the value that's defined there, and do not take into account overriding definitions. In other words, a block of early definitions is evaluated exactly as if it was a local bock containing a number of value definitions. Early definitions are evaluated in the order they are being defined before the superclass constructor of the template is called. ###### Example Early definitions are particularly useful for traits, which do not have normal constructor parameters. Example: scala trait Greeting { val name: String val msg = "How are you, "+name } class C extends { val name = "Bob" } with Greeting { println(msg) }  In the code above, the field name is initialized before the constructor of Greeting is called. Therefore, field msg in class Greeting is properly initialized to "How are you, Bob". If name had been initialized instead in C's normal class body, it would be initialized after the constructor of Greeting. In that case, msg would be initialized to "How are you, ". ## Modifiers ebnf Modifier ::= LocalModifier | AccessModifier | override' LocalModifier ::= abstract' | final' | sealed' | implicit' | lazy' AccessModifier ::= (private' | protected') [AccessQualifier] AccessQualifier ::= [' (id | this') ]'  Member definitions may be preceded by modifiers which affect the accessibility and usage of the identifiers bound by them. If several modifiers are given, their order does not matter, but the same modifier may not occur more than once. Modifiers preceding a repeated definition apply to all constituent definitions. The rules governing the validity and meaning of a modifier are as follows. ### private The private modifier can be used with any definition or declaration in a template. Such members can be accessed only from within the directly enclosing template and its companion module or [companion class](#object-definitions). A private modifier can be _qualified_ with an identifier $C$ (e.g. private[$C$]) that must denote a class or package enclosing the definition. Members labeled with such a modifier are accessible respectively only from code inside the package $C$ or only from code inside the class $C$ and its [companion module](#object-definitions). A different form of qualification is private[this]. A member $M$ marked with this modifier is called _object-protected_; it can be accessed only from within the object in which it is defined. That is, a selection $p.M$ is only legal if the prefix is this or $O$.this, for some class $O$ enclosing the reference. In addition, the restrictions for unqualified private apply. Members marked private without a qualifier are called _class-private_, whereas members labeled with private[this] are called _object-private_. A member _is private_ if it is either class-private or object-private, but not if it is marked private[$C$] where $C$ is an identifier; in the latter case the member is called _qualified private_. Class-private or object-private members may not be abstract, and may not have protected or override modifiers. They are not inherited by subclasses and they may not override definitions in parent classes. ### protected The protected modifier applies to class member definitions. Protected members of a class can be accessed from within - the template of the defining class, - all templates that have the defining class as a base class, - the companion module of any of those classes. A protected modifier can be qualified with an identifier $C$ (e.g. protected[$C$]) that must denote a class or package enclosing the definition. Members labeled with such a modifier are also accessible respectively from all code inside the package $C$ or from all code inside the class $C$ and its [companion module](#object-definitions). A protected identifier $x$ may be used as a member name in a selection $r$.$x$ only if one of the following applies: - The access is within the template defining the member, or, if a qualification $C$ is given, inside the package $C$, or the class $C$, or its companion module, or - $r$ is one of the reserved words this and super, or - $r$'s type conforms to a type-instance of the class which contains the access. A different form of qualification is protected[this]. A member $M$ marked with this modifier is called _object-protected_; it can be accessed only from within the object in which it is defined. That is, a selection $p.M$ is only legal if the prefix is this or $O$.this, for some class $O$ enclosing the reference. In addition, the restrictions for unqualified protected apply. ### override The override modifier applies to class member definitions or declarations. It is mandatory for member definitions or declarations that override some other concrete member definition in a parent class. If an override modifier is given, there must be at least one overridden member definition or declaration (either concrete or abstract). ### abstract override The override modifier has an additional significance when combined with the abstract modifier. That modifier combination is only allowed for value members of traits. We call a member $M$ of a template _incomplete_ if it is either abstract (i.e. defined by a declaration), or it is labeled abstract and override and every member overridden by $M$ is again incomplete. Note that the abstract override modifier combination does not influence the concept whether a member is concrete or abstract. A member is _abstract_ if only a declaration is given for it; it is _concrete_ if a full definition is given. ### abstract The abstract modifier is used in class definitions. It is redundant for traits, and mandatory for all other classes which have incomplete members. Abstract classes cannot be [instantiated](06-expressions.html#instance-creation-expressions) with a constructor invocation unless followed by mixins and/or a refinement which override all incomplete members of the class. Only abstract classes and traits can have abstract term members. The abstract modifier can also be used in conjunction with override for class member definitions. In that case the previous discussion applies. ### final The final modifier applies to class member definitions and to class definitions. A final class member definition may not be overridden in subclasses. A final class may not be inherited by a template. final is redundant for object definitions. Members of final classes or objects are implicitly also final, so the final modifier is generally redundant for them, too. Note, however, that [constant value definitions](04-basic-declarations-and-definitions.html#value-declarations-and-definitions) do require an explicit final modifier, even if they are defined in a final class or object. final may not be applied to incomplete members, and it may not be combined in one modifier list with sealed. ### sealed The sealed modifier applies to class definitions. A sealed class may not be directly inherited, except if the inheriting template is defined in the same source file as the inherited class. However, subclasses of a sealed class can be inherited anywhere. ### lazy The lazy modifier applies to value definitions. A lazy value is initialized the first time it is accessed (which might never happen at all). Attempting to access a lazy value during its initialization might lead to looping behavior. If an exception is thrown during initialization, the value is considered uninitialized, and a later access will retry to evaluate its right hand side. ###### Example The following code illustrates the use of qualified private: scala package outerpkg.innerpkg class Outer { class Inner { private[Outer] def f() private[innerpkg] def g() private[outerpkg] def h() } }  Here, accesses to the method f can appear anywhere within Outer, but not outside it. Accesses to method g can appear anywhere within the package outerpkg.innerpkg, as would be the case for package-private methods in Java. Finally, accesses to method h can appear anywhere within package outerpkg, including packages contained in it. ###### Example A useful idiom to prevent clients of a class from constructing new instances of that class is to declare the class abstract and sealed: scala object m { abstract sealed class C (x: Int) { def nextC = new C(x + 1) {} } val empty = new C(0) {} }  For instance, in the code above clients can create instances of class m.C only by calling the nextC method of an existing m.C object; it is not possible for clients to create objects of class m.C directly. Indeed the following two lines are both in error: scala new m.C(0) // **** error: C is abstract, so it cannot be instantiated. new m.C(0) {} // **** error: illegal inheritance from sealed class.  A similar access restriction can be achieved by marking the primary constructor private ([example](#example-private-constructor)). ## Class Definitions ebnf TmplDef ::= class' ClassDef ClassDef ::= id [TypeParamClause] {Annotation} [AccessModifier] ClassParamClauses ClassTemplateOpt ClassParamClauses ::= {ClassParamClause} [[nl] (' implicit ClassParams )'] ClassParamClause ::= [nl] (' [ClassParams] ')' ClassParams ::= ClassParam {,' ClassParam} ClassParam ::= {Annotation} {Modifier} [(val' | var')] id [:' ParamType] [=' Expr] ClassTemplateOpt ::= extends' ClassTemplate | [[extends'] TemplateBody]  The most general form of class definition is scala class $c$[$\mathit{tps}\,$] $as$ $m$($\mathit{ps}_1$)$\ldots$($\mathit{ps}_n$) extends $t$ $\quad(n \geq 0)$.  Here, - $c$ is the name of the class to be defined. - $\mathit{tps}$ is a non-empty list of type parameters of the class being defined. The scope of a type parameter is the whole class definition including the type parameter section itself. It is illegal to define two type parameters with the same name. The type parameter section [$\mathit{tps}\,$] may be omitted. A class with a type parameter section is called _polymorphic_, otherwise it is called _monomorphic_. - $as$ is a possibly empty sequence of [annotations](11-annotations.html#user-defined-annotations). If any annotations are given, they apply to the primary constructor of the class. - $m$ is an [access modifier](#modifiers) such as private or protected, possibly with a qualification. If such an access modifier is given it applies to the primary constructor of the class. - $(\mathit{ps}\_1)\ldots(\mathit{ps}\_n)$ are formal value parameter clauses for the _primary constructor_ of the class. The scope of a formal value parameter includes all subsequent parameter sections and the template $t$. However, a formal value parameter may not form part of the types of any of the parent classes or members of the class template $t$. It is illegal to define two formal value parameters with the same name. If no formal parameter sections are given, an empty parameter section () is assumed. If a formal parameter declaration $x: T$ is preceded by a val or var keyword, an accessor (getter) [definition](04-basic-declarations-and-definitions.html#variable-declarations-and-definitions) for this parameter is implicitly added to the class. The getter introduces a value member $x$ of class $c$ that is defined as an alias of the parameter. If the introducing keyword is var, a setter accessor [$x$_=](04-basic-declarations-and-definitions.html#variable-declarations-and-definitions) is also implicitly added to the class. In invocation of that setter $x$_=($e$) changes the value of the parameter to the result of evaluating $e$. The formal parameter declaration may contain modifiers, which then carry over to the accessor definition(s). When access modifiers are given for a parameter, but no val or var keyword, val is assumed. A formal parameter prefixed by val or var may not at the same time be a [call-by-name parameter](04-basic-declarations-and-definitions.html#by-name-parameters). - $t$ is a [template](#templates) of the form  $sc$ with $mt_1$ with $\ldots$ with $mt_m$ { $\mathit{stats}$ } // $m \geq 0$  which defines the base classes, behavior and initial state of objects of the class. The extends clause extends $sc$ with $mt_1$ with $\ldots$ with $mt_m$ can be omitted, in which case extends scala.AnyRef is assumed. The class body { $\mathit{stats}$ } may also be omitted, in which case the empty body {} is assumed. This class definition defines a type $c$[$\mathit{tps}\,$] and a constructor which when applied to parameters conforming to types $\mathit{ps}$ initializes instances of type $c$[$\mathit{tps}\,$] by evaluating the template $t$. ###### Example – val and var parameters The following example illustrates val and var parameters of a class C: scala class C(x: Int, val y: String, var z: List[String]) val c = new C(1, "abc", List()) c.z = c.y :: c.z  ###### Example – Private Constructor The following class can be created only from its companion module. scala object Sensitive { def makeSensitive(credentials: Certificate): Sensitive = if (credentials == Admin) new Sensitive() else throw new SecurityViolationException } class Sensitive private () { ... }  ### Constructor Definitions ebnf FunDef ::= this' ParamClause ParamClauses (=' ConstrExpr | [nl] ConstrBlock) ConstrExpr ::= SelfInvocation | ConstrBlock ConstrBlock ::= {' SelfInvocation {semi BlockStat} }' SelfInvocation ::= this' ArgumentExprs {ArgumentExprs}  A class may have additional constructors besides the primary constructor. These are defined by constructor definitions of the form def this($\mathit{ps}_1$)$\ldots$($\mathit{ps}_n$) = $e$. Such a definition introduces an additional constructor for the enclosing class, with parameters as given in the formal parameter lists $\mathit{ps}_1 , \ldots , \mathit{ps}_n$, and whose evaluation is defined by the constructor expression $e$. The scope of each formal parameter is the subsequent parameter sections and the constructor expression $e$. A constructor expression is either a self constructor invocation this($\mathit{args}_1$)$\ldots$($\mathit{args}_n$) or a block which begins with a self constructor invocation. The self constructor invocation must construct a generic instance of the class. I.e. if the class in question has name $C$ and type parameters [$\mathit{tps}\,$], then a self constructor invocation must generate an instance of $C$[$\mathit{tps}\,$]; it is not permitted to instantiate formal type parameters. The signature and the self constructor invocation of a constructor definition are type-checked and evaluated in the scope which is in effect at the point of the enclosing class definition, augmented by any type parameters of the enclosing class and by any [early definitions](#early-definitions) of the enclosing template. The rest of the constructor expression is type-checked and evaluated as a function body in the current class. If there are auxiliary constructors of a class $C$, they form together with $C$'s primary [constructor](#class-definitions) an overloaded constructor definition. The usual rules for [overloading resolution](06-expressions.html#overloading-resolution) apply for constructor invocations of $C$, including for the self constructor invocations in the constructor expressions themselves. However, unlike other methods, constructors are never inherited. To prevent infinite cycles of constructor invocations, there is the restriction that every self constructor invocation must refer to a constructor definition which precedes it (i.e. it must refer to either a preceding auxiliary constructor or the primary constructor of the class). ###### Example Consider the class definition scala class LinkedList[A]() { var head = _ var tail = null def isEmpty = tail != null def this(head: A) = { this(); this.head = head } def this(head: A, tail: List[A]) = { this(head); this.tail = tail } }  This defines a class LinkedList with three constructors. The second constructor constructs an singleton list, while the third one constructs a list with a given head and tail. ### Case Classes ebnf TmplDef ::= case' class' ClassDef  If a class definition is prefixed with case, the class is said to be a _case class_. The formal parameters in the first parameter section of a case class are called _elements_; they are treated specially. First, the value of such a parameter can be extracted as a field of a constructor pattern. Second, a val prefix is implicitly added to such a parameter, unless the parameter carries already a val or var modifier. Hence, an accessor definition for the parameter is [generated](#class-definitions). A case class definition of $c$[$\mathit{tps}\,$]($\mathit{ps}_1\,$)$\ldots$($\mathit{ps}_n$) with type parameters $\mathit{tps}$ and value parameters $\mathit{ps}$ implies the definition of a companion object, which serves as an [extractor object](08-pattern-matching.html#extractor-patterns). It has the following shape: scala object $c$ { def apply[$\mathit{tps}\,$]($\mathit{ps}_1\,$)$\ldots$($\mathit{ps}_n$): $c$[$\mathit{tps}\,$] = new $c$[$\mathit{Ts}\,$]($\mathit{xs}_1\,$)$\ldots$($\mathit{xs}_n$) def unapply[$\mathit{tps}\,$]($x$: $c$[$\mathit{tps}\,$]) = if (x eq null) scala.None else scala.Some($x.\mathit{xs}_{11}, \ldots , x.\mathit{xs}_{1k}$) }  Here, $\mathit{Ts}$ stands for the vector of types defined in the type parameter section $\mathit{tps}$, each $\mathit{xs}\_i$ denotes the parameter names of the parameter section $\mathit{ps}\_i$, and $\mathit{xs}\_{11}, \ldots , \mathit{xs}\_{1k}$ denote the names of all parameters in the first parameter section $\mathit{xs}\_1$. If a type parameter section is missing in the class, it is also missing in the apply and unapply methods. If the companion object $c$ is already defined, the apply and unapply methods are added to the existing object. If the object $c$ already has a [matching](#definition-matching) apply (or unapply) member, no new definition is added. The definition of apply is omitted if class $c$ is abstract. If the case class definition contains an empty value parameter list, the unapply method returns a Boolean instead of an Option type and is defined as follows: scala def unapply[$\mathit{tps}\,$]($x$: $c$[$\mathit{tps}\,$]) = x ne null  The name of the unapply method is changed to unapplySeq if the first parameter section $\mathit{ps}_1$ of $c$ ends in a [repeated parameter](04-basic-declarations-and-definitions.html#repeated-parameters). A method named copy is implicitly added to every case class unless the class already has a member (directly defined or inherited) with that name, or the class has a repeated parameter. The method is defined as follows: scala def copy[$\mathit{tps}\,$]($\mathit{ps}'_1\,$)$\ldots$($\mathit{ps}'_n$): $c$[$\mathit{tps}\,$] = new $c$[$\mathit{Ts}\,$]($\mathit{xs}_1\,$)$\ldots$($\mathit{xs}_n$)  Again, $\mathit{Ts}$ stands for the vector of types defined in the type parameter section $\mathit{tps}$ and each $xs_i$ denotes the parameter names of the parameter section $ps'_i$. The value parameters $ps'_{1,j}$ of first parameter list have the form $x_{1,j}$:$T_{1,j}$=this.$x_{1,j}$, the other parameters $ps'_{i,j}$ of the copy method are defined as $x_{i,j}$:$T_{i,j}$. In all cases $x_{i,j}$ and $T_{i,j}$ refer to the name and type of the corresponding class parameter $\mathit{ps}_{i,j}$. Every case class implicitly overrides some method definitions of class [scala.AnyRef](12-the-scala-standard-library.html#root-classes) unless a definition of the same method is already given in the case class itself or a concrete definition of the same method is given in some base class of the case class different from AnyRef. In particular: - Method equals: (Any)Boolean is structural equality, where two instances are equal if they both belong to the case class in question and they have equal (with respect to equals) constructor arguments (restricted to the class's _elements_, i.e., the first parameter section). - Method hashCode: Int computes a hash-code. If the hashCode methods of the data structure members map equal (with respect to equals) values to equal hash-codes, then the case class hashCode method does too. - Method toString: String returns a string representation which contains the name of the class and its elements. ###### Example Here is the definition of abstract syntax for lambda calculus: scala class Expr case class Var (x: String) extends Expr case class Apply (f: Expr, e: Expr) extends Expr case class Lambda(x: String, e: Expr) extends Expr  This defines a class Expr with case classes Var, Apply and Lambda. A call-by-value evaluator for lambda expressions could then be written as follows. scala type Env = String => Value case class Value(e: Expr, env: Env) def eval(e: Expr, env: Env): Value = e match { case Var (x) => env(x) case Apply(f, g) => val Value(Lambda (x, e1), env1) = eval(f, env) val v = eval(g, env) eval (e1, (y => if (y == x) v else env1(y))) case Lambda(_, _) => Value(e, env) }  It is possible to define further case classes that extend type Expr in other parts of the program, for instance scala case class Number(x: Int) extends Expr  This form of extensibility can be excluded by declaring the base class Expr sealed; in this case, all classes that directly extend Expr must be in the same source file as Expr. ## Traits ebnf TmplDef ::= trait' TraitDef TraitDef ::= id [TypeParamClause] TraitTemplateOpt TraitTemplateOpt ::= extends' TraitTemplate | [[extends'] TemplateBody]  A trait is a class that is meant to be added to some other class as a mixin. Unlike normal classes, traits cannot have constructor parameters. Furthermore, no constructor arguments are passed to the superclass of the trait. This is not necessary as traits are initialized after the superclass is initialized. Assume a trait $D$ defines some aspect of an instance $x$ of type $C$ (i.e. $D$ is a base class of $C$). Then the _actual supertype_ of $D$ in $x$ is the compound type consisting of all the base classes in $\mathcal{L}(C)$ that succeed $D$. The actual supertype gives the context for resolving a [super reference](06-expressions.html#this-and-super) in a trait. Note that the actual supertype depends on the type to which the trait is added in a mixin composition; it is not statically known at the time the trait is defined. If $D$ is not a trait, then its actual supertype is simply its least proper supertype (which is statically known). ###### Example The following trait defines the property of being comparable to objects of some type. It contains an abstract method < and default implementations of the other comparison operators <=, >, and >=. scala trait Comparable[T <: Comparable[T]] { self: T => def < (that: T): Boolean def <=(that: T): Boolean = this < that || this == that def > (that: T): Boolean = that < this def >=(that: T): Boolean = that <= this }  ###### Example Consider an abstract class Table that implements maps from a type of keys A to a type of values B. The class has a method set to enter a new key / value pair into the table, and a method get that returns an optional value matching a given key. Finally, there is a method apply which is like get, except that it returns a given default value if the table is undefined for the given key. This class is implemented as follows. scala abstract class Table[A, B](defaultValue: B) { def get(key: A): Option[B] def set(key: A, value: B) def apply(key: A) = get(key) match { case Some(value) => value case None => defaultValue } }  Here is a concrete implementation of the Table class. scala class ListTable[A, B](defaultValue: B) extends Table[A, B](defaultValue) { private var elems: List[(A, B)] def get(key: A) = elems.find(._1.==(key)).map(._2) def set(key: A, value: B) = { elems = (key, value) :: elems } }  Here is a trait that prevents concurrent access to the get and set operations of its parent class: scala trait SynchronizedTable[A, B] extends Table[A, B] { abstract override def get(key: A): B = synchronized { super.get(key) } abstract override def set((key: A, value: B) = synchronized { super.set(key, value) } }  Note that SynchronizedTable does not pass an argument to its superclass, Table, even though Table is defined with a formal parameter. Note also that the super calls in SynchronizedTable's get and set methods statically refer to abstract methods in class Table. This is legal, as long as the calling method is labeled [abstract override](#modifiers). Finally, the following mixin composition creates a synchronized list table with strings as keys and integers as values and with a default value 0: scala object MyTable extends ListTable[String, Int](0) with SynchronizedTable  The object MyTable inherits its get and set method from SynchronizedTable. The super calls in these methods are re-bound to refer to the corresponding implementations in ListTable, which is the actual supertype of SynchronizedTable in MyTable. ## Object Definitions ebnf ObjectDef ::= id ClassTemplate  An object definition defines a single object of a new class. Its most general form is object $m$ extends $t$. Here, $m$ is the name of the object to be defined, and $t$ is a [template](#templates) of the form scala $sc$ with $mt_1$ with $\ldots$ with $mt_n$ { $\mathit{stats}$ }  which defines the base classes, behavior and initial state of $m$. The extends clause extends $sc$ with $mt_1$ with $\ldots$ with $mt_n$ can be omitted, in which case extends scala.AnyRef is assumed. The class body { $\mathit{stats}$ } may also be omitted, in which case the empty body {} is assumed. The object definition defines a single object (or: _module_) conforming to the template $t$. It is roughly equivalent to the following definition of a lazy value: scala lazy val $m$ = new $sc$ with $mt_1$ with $\ldots$ with $mt_n$ { this: $m.type$ => $\mathit{stats}$ }  Note that the value defined by an object definition is instantiated lazily. The new $m$\$cls constructor is evaluated not at the point of the object definition, but is instead evaluated the first time$m$is dereferenced during execution of the program (which might be never at all). An attempt to dereference$m$again in the course of evaluation of the constructor leads to a infinite loop or run-time error. Other threads trying to dereference$m$while the constructor is being evaluated block until evaluation is complete. The expansion given above is not accurate for top-level objects. It cannot be because variable and method definition cannot appear on the top-level outside of a [package object](09-top-level-definitions.html#package-objects). Instead, top-level objects are translated to static fields. ###### Example Classes in Scala do not have static members; however, an equivalent effect can be achieved by an accompanying object definition E.g. scala abstract class Point { val x: Double val y: Double def isOrigin = (x == 0.0 && y == 0.0) } object Point { val origin = new Point() { val x = 0.0; val y = 0.0 } }  This defines a class Point and an object Point which contains origin as a member. Note that the double use of the name Point is legal, since the class definition defines the name Point in the type name space, whereas the object definition defines a name in the term namespace. This technique is applied by the Scala compiler when interpreting a Java class with static members. Such a class$C$is conceptually seen as a pair of a Scala class that contains all instance members of$C$and a Scala object that contains all static members of$C\$. Generally, a _companion module_ of a class is an object which has the same name as the class and is defined in the same scope and compilation unit. Conversely, the class is called the _companion class_ of the module. Very much like a concrete class definition, an object definition may still contain declarations of abstract type members, but not of abstract term members.


text:
Contents

category theory

# Contents

## Idea

The principle of functional extensionality states that two functions are equal if their values are equal at every argument.

## Definition

### In set theory

In set theory, in the same way that the axiom of choice has internal and external versions, depending on whether one uses the external logic? or the internal logic of the set theory, function extensionality also has internal and external versions.

#### External function extensionality

In set theory, let $\mathbb{1}$ denote the unique singleton up to bijection. There are multiple notions of external function extensionality, due to the different possible notions of function and element in set theory:

• for all sets $A$ and $B$ and functions $f:A \to B$ and $g:A \to B$, $f = g$ if and only if for all elements $x \in A$, $f(x) = g(x)$.

• for all sets $A$ and $B$ and functions $f:A \to B$ and $g:A \to B$, $f = g$ if and only if for all functions $x:\mathbb{1} \to A$, $f \circ x = g \circ x$.

• for all sets $A$ and $B$ and elements of the function set $f \in B^A$ and $g \in B^A$, $f = g$ if and only if for all elements $x \in A$, $\mathrm{ev}_{A, B}(f, x) = \mathrm{ev}_{A, B}(g, x)$.

• for all sets $A$ and $B$ and elements of the function set $f \in B^A$ and $g \in B^A$, $f = g$ if and only if for all elements of the function set $x \in A^\mathbb{1}$, $\mathrm{comp}_{\mathbb{1}, A, B}(f, x) = \mathrm{comp}_{\mathbb{1}, A, B}(g, x)$.

The first is the one most commonly found in foundations of categorical set theories with separate notions of element and function. The second is the one most commonly found in foundations of categorical set theories where an element is defined as a function out of the terminal set $\mathbb{1}$.

The first and the third notions of function extensionality are equivalent to each other, since for every set theory with function sets, the category of sets is a cartesian closed category, which means that there is a bijection between the hom-sets

$\mathrm{Hom}(X, Y) \cong \mathrm{Hom}(1, Y^X)$

and thus for every function $f:X \to Y$ there is a unique element of a function set $[f] \in Y^X$, and for every element of a function set $g \in Y^X$ there is a unique function $g':X \to Y$.

#### Internal function extensionality

In set theory, let $\mathbb{1}$ denote the unique singleton up to bijection and let $\prod_{x \in A} B_x$ denote the Cartesian product of a family of sets $(B_x)_{x \in A}$. For all sets $A$, let $\Delta_{A}:A \to A \times A$ denote the diagonal function; this means that the preimage of $\Delta_{A}$ at $(x, y) \in A \times A$, $\Delta_{A}^*(x, y)$, is a subsingleton, and $(\Delta_{A}^*(x, y))_{x \in A, y \in A}$ is a family of sets.

The principle of internal function extensionality is given by one of the two equivalent statements:

• given sets $A$ and $B$, one can derive the element of the set

$\mathrm{funext}_{A, B} \in \prod_{f \in B^A} \prod_{g \in B^A} \Delta_{B^A}^*(f, g)^{\prod_{x \in A} \Delta_{B}^*(\mathrm{ev}_{A, B}(f, x), \mathrm{ev}_{A, B}(g, x))}$
• given sets $A$ and $B$, one can derive the element of the set

$\mathrm{funext}_{A, B} \in \prod_{f \in B^A} \prod_{g \in B^A} \Delta_{B^A}^*(f, g)^{\prod_{x \in A^\mathbb{1}} \Delta_{B^\mathbb{1}}^*(\mathrm{comp}_{\mathbb{1}, A, B}(f, x), \mathrm{comp}_{\mathbb{1}, A, B}(g, x))}$

This is the set theoretic analogue of the axiom of function extensionality found in dependent type theories, where functions are elements of function types, the type theoretic analogue of function sets, and equalities are represented by identity types, the type theoretic analogue of the diagonal one-to-one correspondence, and is true in any set theory with Cartesian products of arbitrary families of sets as well as function sets.

### In category theory

#### Generalizing external function extensionality

There are multiple ways to extend the set-theoretic definition of external function extensionality from the category of sets to more general categories.

• The first notion of external function extensionality extends from the category of sets to any concrete category $C$, where objects are specific kinds of sets (such as groups, rings, topological spaces, et cetera) and morphisms are specific kinds of functions between sets (such as group homomorphisms, ring homomorphisms, continuous maps, et cetera).

• The second notion of external function extensionality extends from the category of sets to any well-pointed category $C$, and corresponds to the statement that the terminal object is an extremal generator in category, and is one of the conditions for making a pretopos a well-pointed pretopos. This definition is satisfied in any concrete category $\mathcal{C}$. This is not the same as the first notion of external function extensionality, since not every concrete category is well-pointed, and not every well-pointed category is concrete: Grp is concrete but not well-pointed, while an arbitrary model of ETCS is well-pointed but not necessarily concrete.

• The third and fourth notions of external function extensionality extends from the category of sets to any concrete cartesian closed category $C$, and is equivalent to the first notion in any concrete cartesian closed category.

None of these notions are called “function extensionality” in category theory. The term “function extensionality” is reserved for the generalization of internal function extensionality to arbitrary categories, as documented in the next section.

#### Generalizing internal function extensionality

The notion of function extensionality in a category arises from the generalization of the set-theoretic definition of internal function extensionality from the category of sets to more general categories. In particular, similar to internal function extensionality, it the logical formulation of function extensionality in the internal language of the category. The “internal” formulation can be interpreted in a category with a rich enough internal language. For instance, function extensionality can be stated in the Mitchell-Benabou language and is true in any topos. So every topos internally satisfies function extensionality despite the fact that toposes do not generally satisfy the external notion of being concrete or well-pointed. This is because the quantifier $\forall x:X$ in the internal language is interpreted as a quantification over all generalized elements $I \to X$ rather than merely the global elements $1 \to X$. Then the statement when quantifying over generalized elements is true as a consequence of the definition of an exponential object.

### In dependent type theory

In intensional type theory, the notion of equality $a = a'$ is replaced by identifications, these being terms of identity type $Id_A(a,a')$. Since such identity type are in general not mere propositions, care needs to be exercised in stating function extensionality in intensional type theory:

For types $A, B \,\colon\, Type$ and parallel functions $f, g \,\colon\, A \to B$, there are the following two canonical functions (from identity types of function types to dependent products of pointwise identity types), which one may use for expressing function extensionality (2), both defined via path induction (see function application to identifications) as shown now:

(1)$\begin{array}{ll} \mathrm{happly}(f, g) &\colon& Id_{(A \to B)} (f ,\, g) & \longrightarrow & \underset{ a \colon A } {\prod} Id_B \big( f(a) ,\, g(a) \big) \\ \mathrm{happly}(f,f) &\colon& \mathrm{refl}_{(A \to B)}(f) &\mapsto& \lambda (a \colon A). \mathrm{refl}_B \big(f(a)\big) \\ \phantom{-} \\ \mathrm{happly}(f, g) &\colon& Id_{(A \to B)}(f, g) & \longrightarrow & \underset{a \colon A}{\prod} \; \underset{a' \colon A}{\prod} \prod_{p \colon Id_A(a,a')} Id_B \big( f(a) ,\, g(a') \big) \\ \mathrm{happly}(f,f) &\colon& \mathrm{refl}_{A \to B}(f) &\mapsto& \lambda (a \colon A). \lambda (a \colon A). \lambda \big( \mathrm{refl}_A(x) \colon Id_A(a, a) \big). \mathrm{refl}_B\big(f(a)\big) \end{array}$

(These two definitions of $\mathrm{happly}$ become the same under singleton contractibility. The second definition behaves better with the function application to identifications.)

In general, both functions $\mathrm{happly}(f, g)$ are not equivalences of types in intensional type theory: two functions could be defined in different ways, and thus be intensionally different, yet produce the same values on all inputs (i.e. be extensionally the same).

Function extensionality is then the statement that the function $\mathrm{happly}(f, g)$ (1) is an equivalence of types after all, for all functions $f, g \,\colon\,A \to B$:

(2)$\mathrm{funext}(f, g) \;\colon\; \mathrm{isEquiv} \big( \mathrm{happly}(f, g) \big)$

(e.g. UFP13 (2.9.1)).

In the generality of dependent functions $f,g \,:\, (d \colon D) \to C_d$ (using the notation here) this reads:

(In this dependent generality this is a special case of UFP13, Lem. 2.9.7.)

Compare this to the analogous extensionality principle for dependent pairs (see there):

### Judgmental function extensionality

One could replace the equivalences of types above with judgmental equality of types, which results in judgmental function extensionality. Applied to each definition, judgmental function extensionality states that for all all types $A$ and $B$ and functions $f:A \to B$ and $g:A \to B$

$Id_{(A \to B)}(f, g) \;\;\equiv\; \prod_{x:A} id_B\big( f(x) ,\, g(x) \big)$

and

$Id_{(A \to B)} (f ,\, g) \;\equiv\; \prod_{x:A} \prod_{y:A} \prod_{p \colon Id_A(x, y)} Id_B\big( f(x) ,\, g(y) \big)$

respectively.

### For judgmental equality of sections

Suppose that given functions $f:A \to B$ and $g:A \to B$, for all $x:A$, $f(x)$ and $g(x)$ are judgmentally equal to each other $f(x) \equiv g(x):B$. Then it follows that $f$ and $g$ are judgmentally equal to each other, $f \equiv g:A \to B$, and thus function extensionality holds. This result is crucial in the proof of function extensionality from an interval type with judgmental computation rules.

## Properties

There are a number of axioms in dependent type theory which imply function extensionality. These include

### Relation to weak function extensionality

Function extensionality is equivalent to weak function extensionality – see at References – General.

### Relation to the univalence axiom

In homotopy type theory, the univalence axiom implies type-theoretic function extensionality (2) – see at References – in HoTT.

### Relation to interval types

Postulating an interval type with judgmental computation rules for the point constructors of the interval type implies function extensionality.

The proof assumes a typal uniqueness rule for function types. Let $\mathrm{ap}_f \colon Id_{\mathbb{I}}(0, 1) \to Id_A(f(0),f(1))$ be the function application to identities, $\mathrm{concat}_{a, b, c}: Id_A(a , b) \times Id_A(b , c) \to Id_A(a , c)$ be concatenation of identities (i.e. transitivity), and $\mathrm{inv}_{a, b}: Id_A(a , b) \to Id_A(b , a)$ be the inverse of identities (i.e. symmetry).

First the proof constructs a function $k:A \to (\mathbb{I} \to B)$ from a dependent function $h:\prod_{x:A} Id_B\big(f(x) , g(x)\big)$, inductively defined by

• $\beta_{k(x)}^0 : Id_B\big(k(x)(0) , f(x)\big)$

• $\beta_{k(x)}^1 : Id_B\big( k(x)(1) , g(x) \big)$

• $\beta_{k(x)}^p : Id_{Id_B\big(k(x)(0) , k(x)(1)\big)}\big(\mathrm{ap}_{k(x)}(p) , \mathrm{concat}_{k(x)(0), f(x), k(x)(1)}(\mathrm{concat}_{k(x)(0), f(x), g(x)}(\beta_{k(x)}^0, h(x)), \mathrm{inv}_{k(x)(1), g(x)}(\beta_{k(x)}^1))\big)$

Then it uses the properties of function types, product types, currying, uncurrying, and the symmetry of products $A \times B \simeq B \times A$, to construct a function $k':\mathbb{I} \to (A \to B)$, inductively defined by

• $\beta_{k'}^0(x): Id_B\big( k'(0)(x) , f(x)\big)$

• $\beta_{k'}^1(x): Id_B\big( k'(1)(x) , g(x) \big)$

• $\beta_{k'}^p(x):\mathrm{ap}_{k'}(p)(x) =_{Id_B\big( k'(0)(x) , k'(1)(x) \big)} \mathrm{concat}_{k'(0)(x), f(x), k'(1)(x)}(\mathrm{concat}_{k'(0)(x), f(x), g(x)}(\beta_{k'}^0(x), h(x)), \mathrm{inv}_{k'(1)(x), g(x)}(\beta_{k'}^1(x)))$

If the interval type has judgmental computation rules for the point constructors, then $k'(x)(0) \equiv f(x)$ and $k'(x)(1) \equiv g(x)$ for all $x:A$, which implies that $k'(0)(x) \equiv f(x)$ and $k'(1)(x) \equiv g(x)$ for all $x:A$, and subsequently that $k'(0) \equiv f$ and $k'(1) \equiv g$. This means that there are identities $\beta_{k'}^0:k'(0) =_{A \to B} f$ and $\beta_{k'}^1:k'(1) =_{A \to B} g$, and an identity

$\mathrm{concat}_{f, k'(1), g}(\mathrm{concat}_{f, k'(0), k'(1)}(\mathrm{inv}_{k'(0), g}(\beta_{k'}^0), \mathrm{ap}_{k'}(p), \beta_{k'}^1): Id_{(A \to B)}(f , g)$

thus proving function extensionality.

An interval type with only typal computation rules for the point constructors does not imply function extensionality. This is because the proof with the judgmental computation rules uses the fact that $k'(0)(x) \equiv f(x)$ and $k'(1)(x) \equiv g(x)$ for all $x:A$ implies that $k'(0) \equiv f$ and $k'(1) \equiv g$. However, if the computation rules are typal, then the equivalent statement is that having identities $\beta_{k'}^0(x): Id_B\big(k'(0)(x) , f(x)\big)$ and $\beta_{k'}^1(x): Id_B\big(k'(1)(x) , g(x)\big)$ for all $x:A$ implies that there are identities $\beta_{k'}^0: Id_{(A \to B)}\big(k'(0) , f\big)$ and $\beta_{k'}^1 : Id_{A \to B}\big(k'(1) , g\big)$, which is precisely function extensionality, and so cannot be used to prove function extensionality.

### Relation to equality reflection

To do: write how extensional type theory automatically satisfies function extensionality.

### Relation to propositional logic

To do: write how requiring all types to be mere propositions in dependent type theory, such as in propositional logic as a dependent type theory automatically satisfies function extensionality.

### Categorical semantics

Under the standard relation between type theory and category theory, the categorical semantics of the type $\underset{x \colon X}{\prod} Id_Y\big( f(x),\, g(x) \big)$ of pointwise identifications between a pair of parallel functions $f,g \;\colon\; X \to Y$ is the space of sections over (hence the right base change along) $X$ of the pullback

where

Since the right base change is right adjoint to pullback, this means that the categorical semantics of global elements of $\underset{x \colon X}{\prod} Id_Y\big( f(x),\, g(x) \big)$, whose immediate categorical semantics is as maps out of the terminal object (to be denoted “$\ast$”):

is equivalently given by maps of the form

These in turn (now by the defining universal property of the pullback) are equivalent to maps of the form

hence to lifts of $(f,g)$ through the path fibration display map.

In contrast, the categorical semantics of the global type of identifications $Id_{(X \to Y)}(f,g)$ is by maps of the form

where

So the categorical semantics of function extensionality (2) says in particular that there is a map

$\phi \;\colon\; Paths\big(Maps(X,Y)\big) \longrightarrow Maps\big(X, Paths(Y) \big)$

which serves to lift global elements as above.

Of course we are not just interested in global elements here. What we really want is an actual section $Maps\big(X, Paths(Y)\big) \to Paths\big(Maps(X,Y)\big)$ of $\phi$ in the slice over $Maps\big(X, (Y \times Y)\big)$ (although this can be derived from the global element formulation by using the Yoneda lemma together with currying and uncurrying tricks), such that this exhibits a weak equivalence.

###### Proposition

Function extensionality holds in the internal type theory of a type-theoretic fibration category precisely if dependent products (i.e. right base change) along fibrations preserve acyclic fibrations.

###### Example

The condition in prop. holds in particular in right proper Cisinski model structures, since in these right base change along fibrations is a right Quillen functor (see e.g. the proof here).

Notice that every presentable locally Cartesian closed (∞,1)-category (by the discussion there) has a presentation by a right proper Cisinski model category. Accordingly we may say that every presentable locally Cartesian closed (∞,1)-category interprets HoTT+FunExt.

## References

### General

Discussion of variants of function extensionality in Martin-Löf type theory, and their relation:

Proofs of function extensionality from an interval type with judgmental computation rules:

### In homotopy type theory

Discussion of function extensionality in homotopy type theory and proof that it is implied by univalence:

Original announcement in:

Textbook accounts:

Exposition:

Tutorial for formalization in Coq:

Formalization in cubical Agda:

Discussion of the categorical semantics in the context of homotopy type theory:

On definitional function extensionality in higher observational type theory:

Last revised on January 21, 2023 at 10:01:00. See the history of this page for a list of all contributions to it.


text:
# PHP Questions

Q:

How to use HTTP Headers inside PHP? Write the statement through which it can be added?

HTTP headers can be used in PHP by redirection which is written as:

The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement above gets included at the top of the script.

Subject: PHP - Technology

15755
Q:

Why was PHP developed, what it is used for, and where can you get it?

PHP developed for less script, time saving, Free Open Source Software and runs on different platforms such as Windows, Linux, Unix, etc. PHP compatible with almost all servers used today such as Apache, IIS, etc.

The PHP scripting language resembles JavaScript, Java, and Perl, These languages all share a common ancestor, the C programming language. PHP has full access to the information that the server has, and very little access to information that the client has. In fact, it only has information that the client tells the server and that the server passes on to PHP. Because it is on the server, however, PHP cannot be modified by the client. While you cannot necessarily trust the information that the client gives to PHP, you can trust that your PHP is doing what you told it to do. Because PHP is on the server end, your PHP scripts can affect your server -- such as by keeping an activity log or updating a database.

Subject: PHP - Technology

7455
Q:

What type of inheritance that PHP supports? Provide an example.

PHP supports single level inheritance.

Inheriting a class would mean creating a new class with all functionality of the existing class in addition to some more. The created class is called as a subclass of the parent class. Parent is a keyword which we use to access members of a parent class. Inheritance is usually defined by using the keyword “Extend”. $this is used a reference to the calling object. Inheritance avoids redundancy of code. Example: Class employee extends manager : Here Employee is a subclass of manager. Echo$this->name can be used to echo variable name of the parent class.

Subject: PHP - Technology

7208
Q:

What’s the difference between md5( ), crc32( ) and sha1( ) crypto on PHP?

Answer The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

Subject: PHP - Technology

4442
Q:

What is PHP's configuration file called?

PHP’s configuration file is called php.ini.

Subject: PHP - Technology

4132
Q:

I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

Answer PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

Subject: PHP - Technology

3604
Q:

How we get IP address of client,previous reference page etc?

By using $_SERVER['REMOTE_ADDR'],$_['HTTP_REFERER'] etc.

Subject: PHP - Technology

3157
Q:

$message vs $$message in PHP? Answer message is a variable with a fixed name.$$message is a variable whose name is stored in$message.

If $message contains "var",$$message is the same as$var.


text:
# Calculating perceived screen resolution in a virtual reality scene

I’m trying to calculate the highest perceived resolution of a virtual screen viewed through a physical screen, given the dimensions of the virtual 3D scene and properties of the physical display.

Specifically, a virtual screen viewed from given distance, with a VR headset of given resolution and field of view.

For example, if I was using a VR headset with 1080x1200 display panel, with horizontal FOV of 110 degrees and I was viewing a virtual 65” 16:9 TV from 2 meters, what would be the true resolution I’m getting out of the TV?

To keep it simple (albeit less correct), it’s not necessary to account for any optics distortion or stereo rendering with dual panels. Let’s just assume pixels are distributed uniformly through the entire FOV.

We'll also assume the screen is flat and facing directly at the camera in the scene, so we don't need to mind any angles or curvature.

I’ll call the provided properties as follows:

HMDPanelResX,    // Display panel horizontal resolution in px
HMDPanelResY,    // Display panel vertical resolution in px
HMDFOVX,         // Horizontal field of view coverage in degrees
VRScreenSizeX,   // Virtual screen width in cm
VRScreenSizeY,   // Virtual screen height in cm
VRScreenDistance // Distance to screen in cm

I know vertical FOV (HMDFOVY) can be derived through the aspect ratio and horizontal FOV. Also getting the pixels per degrees value for each axis is a matter of a simple division.

I think the next step would be to figure out how large portion of the FOV the virtual screen will cover horizontally and vertically with the given dimensions, but I don’t know how to calculate it.

The return values I want to derive can be called VRScreenResX and VRScreenResY.

Assuming you are facing the virtual screen head on, If $\theta$ is the width of the screen in degrees, then the physical width is $w = 2d\sin \frac\theta 2$ where $d$ is the distance to the screen. Solving this for $\theta$ gives $$\theta = 2\sin^{-1}\frac{w}{2d}$$
If $w$ is much smaller than $d$ (say at most 10% of $d$) then this is $$\theta = \frac {180^\circ}{\pi}\frac wd$$ to good approximation. And the smaller $\frac wd$ is, the better the approximation becomes.


text:
GEOGRAPHICAL RESEARCH ›› 2019, Vol. 38 ›› Issue (2): 259-272.

• Articles •

### Spatial-temporal characteristics of innovation output and its influencing factors of the key industries in China

Binyan WANG1(), Shijun WANG1(), Junfeng TIAN2, Feilong HAO1

1. 1. School of Geographical Sciences, Northeast Normal University, Changchun 130024, China
2. College of Earth Sciences, Jilin University, Changchun 130061, China
• Received:2017-04-25 Revised:2018-08-11 Online:2019-02-20 Published:2019-03-08

Abstract:

The innovation, development and technological progress of the ten key industries (iron and steel, automobiles, ships, petrochemicals, textiles, light industry, nonferrous metals, equipment manufacturing, electronic information and logistics) in China are highly concerned by the state and expected by the public. So the research on it is of great significance. Firstly, the Mann-Kendall method is used to divide the development stages of the ten key industries of China from 1994 to 2014, and to understand the evolution of the key industries. Secondly, this paper analyzes the innovation output difference, spatial pattern and spatial-temporal transfer characteristics of key industries in the prefecture-level cities by using the Theil index, Markov and spatial Markov chains method respectively. Finally, based on factor analysis and multiple regression model, this paper discusses the factors that influence the spatial differentiation of the innovation development of the ten key industries in China. The conclusions are drawn as follows: (1) The development of the innovation outputs of the ten key industries can be divided into two stages (the first stage is from 1995 to 2006, the second stage is from 2007 to 2014), and the result of innovation outputs of the ten key industries is in exponential growth. (2) The difference of the innovation outputs of the ten key industries increased at first and then decreased, and the inter-regional difference among the four regions (Eastern, Central, Western and Northeastern China) is less than the intra-regional difference. The development of innovation outputs of the ten key industries presents the dual characteristics of contagious and hierarchical diffusion. (3) The neighborhood environment plays an important role in the development of the ten key industries. Under different environmental constraints, the transition probability of different types of unit is different, and the higher the neighborhood environment level is, the stronger the driving force to low level units is. In the two periods, the transferred units of the innovation outputs of the ten key industries are mainly concentrated in the eastern and central regions of China. The activity of the transfer is increasing, and the transferred units are concentrated in spatial distribution. (4) The social economic and policy factors and the basic condition of higher education have obvious positive driving effect on the innovation and development of the ten key industries, while the effect of industrialization is weak. In the next period of time, the innovation and development competitiveness of the ten key industries can be improved by strengthening the investment in the foundation of higher education and intellectual capital.


text:
# The Q$^2$-Dependence of the Neutron Spin Structure Function g$_2^n$ at Low Q$^2$

Abstract : We present the first measurement of the Q^2-dependence of the neutron spin structure function g_2^n at five kinematic points covering 0.57 (GeV/c)^2 <= Q^2 <= 1.34 (GeV/c)^2 at x~0.2. Though the naive quark-parton model predicts g_2=0, non-zero values for g_2 occur in more realistic models of the nucleon which include quark-gluon correlations, finite quark masses or orbital angular momentum. The sensitivity of g_2 to physics beyond the simple quark-parton model provides a unique opportunity to examine QCD dynamics in nucleon structure. When scattering occurs from a non-interacting quark, a prediction for g_2^n can be calculated using next-to-leading order fits to world data for g_1^n. Our results show a positive deviation from this prediction indicating that contributions such as quark-gluon interactions may be important. Data were also obtained for g_1^n and are consistent with a next-to-leading order fit to world data evolved to our kinematic range.
Document type :
Journal articles

http://hal.in2p3.fr/in2p3-00024256
Contributor : Jeanine Pellet <>
Submitted on : Wednesday, June 15, 2005 - 3:17:49 PM
Last modification on : Thursday, January 11, 2018 - 6:13:50 AM

### Citation

K. Kramer, D. Armstrong, T. Averett, W. Bertozzi, S. Binet, et al.. The Q$^2$-Dependence of the Neutron Spin Structure Function g$_2^n$ at Low Q$^2$. Physical Review Letters, American Physical Society, 2005, 95, pp.142002. ⟨10.1103/PhysRevLett.95.142002⟩. ⟨in2p3-00024256⟩

Record views


text:
Browse Questions

# Which of the following statements is correct?

(a) Sillicon doped with boron is an n-type semiconductor

(b)Sillicon doped with arsenic is a p-type semiconductor

(c) Metals are good conductor of electricity.

(d) Electrical  conductivity of semiconductors decreases with increasing temperature


text:
Using hookes law to find impulse

1. Dec 10, 2011

captainhooke1

1. The problem statement, all variables and given/known data
You are given a FORCE versus TIME graph, which shows oscillations with:

A= 4N at the max points
period is 4s
spring constant (k)= 12.3 N/m
mass of block exhibiting oscillation is 4.9 kg

How do you find the IMPULSE delivered to the block during the 1st 2 seconds of oscillation?

2. Relevant equations:
impulse=Δp
E=kx
x(t)= Acos(wt)
w=2∏f
W=deltaEk or F(D)

3. The attempt at a solution
x(t)=Acos(wt)

x(0)=4cos0=4N
x(2)=4N

I don't know how to connect this information

2. Dec 10, 2011

Delphi51

Welcome to PF, Captain!
Do you have the graph? It depends where it starts - is F=0 at time zero or what?
The usual impulse formula is F*Δt. Your F varies with time; can you integrate F*dt over the Δt?

3. Dec 10, 2011

BetoG93

Find the function F that defines force (it is a sine or cosine, from what you told). Integrate it over the time interval from 0 to 2 seconds.


text:
# SAT Math : How to find the whole from the part with percentage

## Example Questions

← Previous 1

### Example Question #1 : How To Find The Whole From The Part With Percentage

David's trip expenses are pictured in the above pie chart (numbers = % of his total expenses). If he spent $75 on taxis, how much did he spend on hotel and souvenirs combined? Possible Answers:$250

$40$175

$200$225

$200 Explanation: David spent$75 on taxis, which were 15% of his total expenses on the trip. He therefore spent 75(100/15) = $500 on the trip altogether. The hotel and souvenirs make up 35% + 5% = 40% of his total expenses. 40% of 500 is$200.

### Example Question #2 : How To Find The Whole From The Part With Percentage

30% of what number is 20?

Solve to the nearest hundredth.

66.67

1.5

150%

0.67

66.67

Explanation:

This is a very basic form percentage question. This can be rewritten:

0.3 * x = 20

(Remember, the word "of" in a word problem indicates multiplication, while the word "is" indicates an equals sign).

Solve for x: x = 20 / 0.3 = 66.67

A toy is on sale for 43% off. Its sale price is $21.37. What is the full price? Possible Answers: None of the available answers Correct answer: Explanation: An algebraic expression for this item is: ### Example Question #1 : How To Find The Whole From The Part With Percentage Twenty-six students planned to contribute an equal amount to purchase a gift for their teacher. After 18 students had paid, they had collected$76.50. What is the total price of the gift?

Explanation:

If $76.50 had been collected after 18 students had paid, we can determine how much each student contributed:$76.50/18 = $4.25 per student Now we can multiply this by the total number of students (26) to get the full price of the gift: 26 x$4.25 = \$110.50

### Example Question #1 : How To Find The Whole From The Part With Percentage

If  of  is , then what is  of ?

20

10

200

50

100

50

Explanation:

The first part of the problem tells us that x% of 20 is 50. We can model x% as x/100 or 0.01x. To find x% of 20, we can multiply 0.01x and 20. In other words, we can write the following equation:

(0.01x)(20) = 50

Divide both sides by 20.

0.01x = 2.5

Divide both sides by 0.01.

x = 250.

The question then asks us to find 20% of x. We can represent 20% as 0.2, and we know that x is 250. Therefore,

20% of 250 = 0.2(250) = 50.

### Example Question #2 : How To Find The Whole From The Part With Percentage

If  of a number is , what is  of the number?

Explanation:

Let x be the number in question.

Then 2/3 * x = 18.

x = 18 * 3/2 = 27

Now find 1/9 of 27:

1/9 * 27 = 3

### Example Question #1091 : Sat Mathematics

17 is 85% of what number?

Explanation:

In this case, 17 is part of a whole x. We are also given that 17 is 85% of x.

With this in mind, we can set up the following proportion.

To solve for x, cross multiply.

### Example Question #1092 : Sat Mathematics

On the ride home from school, Jim notices that  pecent of the cars he passes are yellow. Jim sees  yellow cars. How many cars does Jim see that aren't yellow?

Explanation:

Let x represent the total number of cars Jim sees on the way home. If Jim sees 7 yellow cars and notices that 35% of all the cars he sees are yellow, then we can express this as

7/x = 35%, or

Using cross multiplication, we see that

Therefore, Jim sees 20 total cars on the way home. The question wants to know how many cars are NOT yellow. We can find that by subtracting the total number of cars from the number of yellow cars:

### Example Question #1093 : Sat Mathematics

is  of what number?

None of the given answers are correct.

Explanation:

To solve this problem, we can set up a proportion and solve for our missing value using cross multiplication.

### Example Question #1094 : Sat Mathematics

is  of what number?

Explanation:

Don't let the pi throw you off on this question. We can set up a proportion to solve for the whole that we are looking for.

(Remember that any percentage can also be written as a fraction.)

Now we can solve for our unknown by using cross multiplication.

Therefore,  is  of

← Previous 1


text:
My Math Forum (http://mymathforum.com/math-forums.php)
-   Elementary Math (http://mymathforum.com/elementary-math/)
-   -   Golf Balls! (http://mymathforum.com/elementary-math/345107-golf-balls.html)

 caddie456 October 9th, 2018 06:22 PM

Golf Balls!

A worker is packaging 177 golf balls into sleeves. Each sleeve can hold 3 golf balls. There are two options for how many sleeves can be packaged into a box:

The first type of box can hold 4 sleeves
The second type of box can hold 5 sleeves

How many boxes and of which type are needed to package all of the golf balls?

(This problem is very simple to do using trial/error, but I'm looking for an algebraic solution)

Thanks

:grin:

 greg1313 October 9th, 2018 06:43 PM

Let f be the number of the first type of box and let s be the number of the second type of box.

12f + 15s = 177. By inspection, f = 1 and s = 11. I don't think there is enough information given to form a second equation relating boxes, balls and sleeves that isn't just a scalar multiple of the above equation.

 v8archie October 9th, 2018 07:56 PM

Written as \begin{align}12(f+s)+3s &= 177 \\ 4(f+s) + s &= 59\end{align}
We see that we require $f+s < 15$ and that we pick $s$ to complete the sum for an appropriate value of $(f+s)$. This gives rise to solutions $(f,s) \in \{ (11,3), (6,7), (1,11) \}$, being the solutions for $(f+s)$ equal to 14, 13 and 12 respectively.

Lower values of $(f+s)$ don't have solutions as they require $s > f+s$ which implies negative values of $f$.

 All times are GMT -8. The time now is 04:43 PM.