Language Atlas (mini-courses for more languages)
Language Atlas flashcards
Flashcards for the Language Atlas: toolchains, idioms and traps of ABAP, VB.NET, Pascal, Ada, Tcl, Objective-C, Groovy, D, Gleam, Nim, Elm and Crystal.
413 cards. Read the question, answer it in your head, then open the card to check.
-
Which four lessons does every Language Atlas language get, in which order?
Setup and where the language is used, its idioms next to a language you already know, its signature feature, and then a small project with tests. Each lesson relies on the ones before it.
From the lesson How the Language Atlas works
-
In a recorded terminal session, which lines are the commands to type?
The lines that follow a $. What sits under a command is its output, and every session opens by asking each tool for its version.
From the lesson How the Language Atlas works
-
Your output differs from a recorded run. What do you compare first?
The version the tool reports against the pin of the session. An output only holds for the version that printed it, so a run on another version says nothing about the program yet.
From the lesson How the Language Atlas works
-
What does expr {010 + 1} print on Tcl 8.5.9, and on Tcl 9.0.4?
9 on Tcl 8.5.9, which takes a leading 0 to mean octal, and 11 on Tcl 9.0.4, where 010 is ten. Tcl 9 spells octal with the prefix 0o.
From the lesson How the Language Atlas works
-
What does a language need before it can join the atlas?
A free toolchain that runs it from a command line, so that each example can show a real run you can repeat, and official documentation to cite.
From the lesson How the Language Atlas works
-
How can the atlas teach ABAP without an SAP system?
Its examples run on the MIT-licensed abaplint transpiler, which turns ABAP into JavaScript for Node.js. The price: it reads 7.02 syntax, and topics only an SAP system can show are marked as such.
From the lesson How the Language Atlas works
-
Why is VBScript left out of the atlas?
It runs only on Windows, and Microsoft lists it as deprecated, to become a feature on demand before it is removed. A course would teach towards a language that is leaving its only platform.
From the lesson How the Language Atlas works
-
What should each of the seven sessions of a language week end with?
A program you ran, with a note of what it printed, rather than a page you read. Dunlosky and colleagues rated practice testing and distributed practice of high utility, and rereading and highlighting of low utility.
From the lesson A one-week plan for learning any language
-
Which seven rows does the concept map of a new language have?
Division and rounding, strings, equality, copying and sharing, absence of a value, errors, and overflow. One short probe program answers five of them in a single run.
From the lesson A one-week plan for learning any language
-
With whole numbers, what is -7 / 2 in Tcl 9, and in Objective-C or with Visual Basic's \?
-4 in Tcl, which rounds the quotient down, and -3 in Objective-C and with Visual Basic's \, which cut towards zero. The remainders are 1 and -1.
From the lesson A one-week plan for learning any language
-
What length does the emoji U+1F600 have in Tcl 9, and in Objective-C or Visual Basic?
1 in Tcl 9, which counts characters, and 2 in Objective-C and Visual Basic, which count UTF-16 units. A 20-character limit therefore fits 20 of them in Tcl but only 10 in the other two.
From the lesson A one-week plan for learning any language
-
A tax works out at exactly 184.5 cents. What do Tcl, Objective-C and Visual Basic's CInt make of it?
185 in Tcl and in Objective-C, which both round halfway cases away from zero, and 184 with CInt, which picks the even neighbour: banker's rounding.
From the lesson A one-week plan for learning any language
-
Why is turning Option Strict Off no fix for error BC30512 on a Visual Basic tax line?
The error goes, the mistake stays: the Double is then narrowed silently with banker's rounding, so 184.5 cents becomes 184. Keep the option on and pick the rule in the line, \ to drop the fraction or CInt to round.
From the lesson A one-week plan for learning any language
-
Two NSStrings both hold "invoice". Why can a == b be false in Objective-C?
== compares the two pointers, so it is true only for one and the same object. isEqualToString: compares the text.
From the lesson A one-week plan for learning any language
-
Two documents disagree about what a language means. Which one do you believe?
The higher one on the ladder, provided both describe the same version: a specification or standard, then the reference manual, then library documentation, then a tutorial. Release notes answer only what changed and when.
From the lesson Reading language references and release notes
-
What does -8 Mod 3 give in Visual Basic, and where is that settled?
-2. The language reference's entry for the Mod operator says the result keeps the sign of the dividend, and a two-line program on the .NET SDK 10.0.401 printed -2, and 2 for 8 Mod -3.
From the lesson Reading language references and release notes
-
Which document settles what -7 / 2 gives in Objective-C?
The C standard, clause 6.5.5: Objective-C is a superset of C and keeps its arithmetic, so the quotient is truncated towards zero. Apple's guide does not answer it.
From the lesson Reading language references and release notes
-
What do Tcl 8.5.9 and Tcl 9.0.4 give for 0042 + 0, and how do you write octal for both?
34 on Tcl 8, which reads the leading zero as octal, and 42 on Tcl 9. Writing 0o42 means octal on both versions and gives 34.
From the lesson Reading language references and release notes
-
Tcl's manual says only that round() works "by rounding". What settles which way a half goes?
The smallest example, run on the pinned version, with the version noted beside the answer. On Tcl 9.0.4, round(0.5) gave 1 and round(-2.5) gave -3: halfway cases went away from zero.
From the lesson Reading language references and release notes
-
May a team copy and adapt the Elm guide for its own handbook?
No. It is under CC BY-NC-ND 4.0: it may be shared unchanged and not commercially, and an adapted version may not be shared. Link to it and write the explanation yourself.
From the lesson Reading language references and release notes
-
Name three Tcl 9.0 changes besides the end of leading-zero octal.
Digits may be grouped with underscores, as in 1_000; ~ no longer means the home folder (file home and file tildeexpand replace it); and a malformed byte in an encoding such as UTF-8 raises an error by default.
From the lesson Reading language references and release notes
-
How does ABAP code run on a laptop without an SAP system?
The abaplint transpiler writes JavaScript from the ABAP files, Node.js runs it with @abaplint/runtime, and open-abap-core, an ABAP library of standard classes such as cl_abap_unit_assert, is transpiled with your code.
From the lesson ABAP without an SAP system: setup and limits
-
Why does the ABAP setup read open-abap-core from a local clone at one commit, not from a url?
Given a url, the transpiler clones the newest commit on every run, so a result could change with no change of yours. A pinned local folder keeps every run repeatable.
From the lesson ABAP without an SAP system: setup and limits
-
Which files does abapGit keep for the class ZCL_ATLAS_HELLO?
zcl_atlas_hello.clas.abap for the source, zcl_atlas_hello.clas.testclasses.abap for its local test classes, and zcl_atlas_hello.clas.xml for what the system keeps beside the code, such as the description.
From the lesson ABAP without an SAP system: setup and limits
-
The ABAP Unit run printed a running line for a test. Did that test pass?
Not necessarily: the line is printed before the test starts. The runner stops at the first failure, so later tests never run, and only exit status 0 says that all of them passed.
From the lesson ABAP without an SAP system: setup and limits
-
What does abaplint's downport rule do, and when is it active?
It rewrites newer syntax, such as NEW and inline DATA( ), as ABAP 7.02 statements. It works only when abaplint.json sets the syntax version v702, and the existing tests then prove the rewrite.
From the lesson ABAP without an SAP system: setup and limits
-
What do sy-sysid, sy-mandt and an AUTHORITY-CHECK give on the transpiler?
Always ABC and 123, and a check that passes with sy-subrc 0. An SAP system gives its own ID, the client you logged on to, and 4 or more when your user lacks the authorisation.
From the lesson ABAP without an SAP system: setup and limits
-
3 * ( 1 / 3 ) is assigned to a variable of type i. What do the transpiler and an SAP system store?
1 on the transpiler, 0 on an SAP system: in calculation type i, SAP rounds every interim result, so 1 / 3 is already 0.
From the lesson ABAP without an SAP system: setup and limits
-
What breaks when an abap_transpile.json has "options": {} instead of keeping addCommonJS?
Transpiling looks fine, but running the tests fails at once with ReferenceError: cl_abap_objectdescr is not defined: without addCommonJS the class modules do not import the classes they depend on.
From the lesson ABAP without an SAP system: setup and limits
-
What does lv_i = 7 / 2. store in an ABAP integer?
4. ABAP rounds the quotient commercially to the calculation type, a half going away from zero, where Java's / drops the fraction and gives 3.
-
What does a field of type c LENGTH 5 keep when you assign Bengaluru to it?
Benga, the first five characters, and nothing warns you. Use string for text of any length, and keep c and n for fields of a fixed length such as codes and keys.
-
How do LOOP AT itab INTO wa and LOOP AT itab ASSIGNING <fs> differ?
INTO copies each line into a work area, so changes stay in the copy. ASSIGNING makes the field symbol another name for the line itself, so writing to it changes the table.
-
What happens when a second line with the same key goes into a hashed table?
It is refused with sy-subrc 4, because a hashed table's key is always unique. Such a table finds a line by its whole key in the same time at any size, but it has no line numbers.
-
What goes wrong with READ TABLE … BINARY SEARCH on a standard table that was never sorted?
The search assumes key order, so it can miss lines that are in the table, without saying so. SORT the table first, or use a sorted table, which keeps key order on every insert.
-
What are -7 DIV 2, 7 DIV -2 and 7 MOD -2 in ABAP?
-4, -3 and 1. ABAP keeps the remainder of DIV and MOD from going negative, which is why 7 DIV -2 is -3: -2 × -3 + 1 = 7.
-
A port of ABAP money code to Java or Python must round halves as ABAP does. What do you use?
BigDecimal with RoundingMode.HALF_UP in Java, or Decimal with ROUND_HALF_UP in Python, both away from zero. Math.round turns -184.5 into -184, and Python's round() turns 184.5 into 184.
-
READ TABLE finds no line. What is left in the work area?
Whatever the previous read put there: SAP leaves it unchanged, so a report can show the last customer next to sy-subrc 4. Test sy-subrc on the very next line, or ask line_exists( ) first.
-
In ABAP Objects, when do you write -> and when =>?
-> reaches the components of an instance, as in lo_account->withdraw( 400 ); => reaches the static components of a class, as in zcl_account=>opened.
-
Why should a test not expect an exact value of a static counter attribute?
A static attribute belongs to the class, so the objects that earlier tests created are still counted. An exact expectation would pass or fail by the order in which tests ran.
-
What happens when a method runs RAISE EXCEPTION TYPE zcx_insufficient_funds?
An object of the exception class is created and the method stops at that line. The exception goes to the nearest TRY whose CATCH matches, and CATCH … INTO puts the object in a variable.
-
What does each ABAP exception category ask of a method that raises it?
CX_STATIC_CHECK: catch it or declare it, which the syntax check verifies. CX_DYNAMIC_CHECK: declare it, checked only when one actually leaves the method. CX_NO_CHECK: no declaration at all.
-
Which RISK LEVEL does an ABAP Unit test class need when its setup inserts rows?
DANGEROUS, the level for tests that change persistent data. HARMLESS changes nothing persistent, and CRITICAL, the default, changes settings; an SAP system skips tests above the level it allows.
-
How can a test of due dates give the same result on every day?
The class asks an interface, zif_clock, for today's date and takes the clock through its constructor. The test passes in a FOR TESTING double that always returns the date the test chose.
-
Why can a SELECT count more rows on the transpiler than on an SAP system?
On the transpiler's SQLite database it reads the rows of every client. On an SAP system, ABAP SQL adds a condition on the client column, so it sees only the client you logged on to.
-
How do you keep an ABAP WHERE condition safe from SQL injection?
Give the value as a host variable in a static statement, such as WHERE customer = @iv_customer, never as text joined into a dynamic token. abaplint's dangerous_statement rule fails the joined version.
-
In the invoice project, which taxes does a line pay within a State, and which between States?
CGST and SGST at half the rate each within a State; IGST at the whole rate between States. The rate is an input of the class, which checks no law.
-
Where should the expected numbers of a money test come from?
From the specification, worked out by hand or by a second program. Copied from a first run of the class, they would only confirm what the class already does.
-
Why does the rounding test of the invoice use taxes of 22.5 and 184.5 paise?
Only an exact half tells the rules apart: half away from zero, cutting and banker's rounding all agree on 90.27. A rule is tested by numbers on which the wrong rules give another answer.
-
Where does the invoice class round each amount?
Once, when a packed result is assigned to a whole-paise field of type i. Because the rate is a packed number, the arithmetic runs in type p, and 1003 × 18.00 / 200 keeps its 90.27 until it is stored as 90.
-
An invoice has three equal lines, each with 90.27 paise of CGST. What do rounding per line and per invoice give?
270 paise rounded per line (90 three times) and 271 rounded once on 270.81. Between States the gap turns round: 543 paise of IGST per line against 542 per invoice.
-
Why does halving a 5 % rate in a variable of type i overcharge the CGST?
Half of 5 is 2.5, which type i rounds to 3, so the line pays 3 % twice: 30 paise of CGST instead of 25. With 18 % the mistake hides, because half of 18 is a whole number.
-
Which two files does abapGit need before it can pull the invoice project into an SAP system?
.abapgit.xml at the root, with the main language, the starting folder /src/ and the folder logic, and package.devc.xml in src with the package's description.
-
How large a total in paise fits in an ABAP field of type i?
2,147,483,647 paise, about 21.47 million rupees. Invoices whose totals may pass that need int8.
-
Which command creates a Visual Basic console project with the .NET SDK, and what does it write?
dotnet new console -lang VB -o hello writes hello.vbproj and Program.vb, a Module whose Sub Main is where the program starts. Leave out -lang VB and the template is C#.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
Which values do the four Visual Basic Options take when the project file is silent?
Explicit On, Strict Off, Infer On and Compare Binary. Those same SDK defaults hide the warnings BC42016 and BC42017, so a careful project writes all four Options out.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
With Option Strict Off, what does Dim half As Integer = 2.5 store?
2, without a warning: the conversion sends a half to the even neighbour. With Option Strict On the same line is compile error BC30512.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
label is declared As Object and Option Strict is Off. What becomes of the typo label.ToUpperr()?
It compiles as a late-bound call and throws MissingMemberException only when the line runs. Declared As String, the same typo is compile error BC30456.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
The project sets OptionStrict On. Can a file still compile with the checks off?
Yes. An Option Strict Off statement at the top of a file overrides the project for that file, so read the first lines of every old file.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
What does "rollForward": "latestPatch" let a global.json that names 10.0.401 use?
10.0.401 or a newer installed patch of the 10.0.4xx feature band, never a 10.0.5xx or 11.0 SDK. If no installed SDK fits the pin, every dotnet command stops.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
Which kinds of work does the .NET 10 SDK still offer Visual Basic templates for?
Console programs, class libraries, unit tests and Windows desktop apps (Windows Forms and WPF). There is no Visual Basic web template, so new web work goes to C#, in the same solution if needed.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
Why does the pinned program take Math.Abs before splitting paise with \ 100 and Mod 100?
Both \ and Mod keep the minus sign of a negative amount, so a refund of -150 paise would print as -1.-50. Split the absolute value and write the sign once.
From the lesson VB.NET on .NET 10: projects and Option Strict
-
How many elements does Dim marks(4) As Integer have, and which values does For i = 1 To 10 Step 3 visit?
Five, indexes 0 to 4, because the number is the last index; the loop visits 1, 4, 7 and 10, its end included. A C# port needs new int[n + 1] and a loop with <=.
From the lesson VB.NET for C# developers: the differences
-
What does Dim count As Integer = Nothing give, and what is "" = Nothing for strings?
0: Nothing is the default of whatever type receives it, like C#'s default. For strings, an empty string equals Nothing, so only Is Nothing asks whether there is a string at all.
From the lesson VB.NET for C# developers: the differences
-
A Sub declares ByRef amount. What does the caller's code show, and how can it pass a copy?
Nothing at the call site shows that the variable may change; C# would make you write ref. Wrapping the argument in an extra pair of parentheses, AddTax((price)), passes a copy.
From the lesson VB.NET for C# developers: the differences
-
Which Visual Basic operators are C#'s && and ||?
AndAlso and OrElse. And and Or evaluate both sides, so x IsNot Nothing And x.Count > 0 throws NullReferenceException when x is Nothing; IIf also evaluates every argument.
From the lesson VB.NET for C# developers: the differences
-
What are CInt(3.5) and C#'s (int)3.5, and which C# call matches CInt?
4 and 3. CInt rounds a half to the even neighbour, the cast drops the fraction, and Convert.ToInt32 rounds the way CInt does.
From the lesson VB.NET for C# developers: the differences
-
What happens at Integer.MaxValue + 1 in Visual Basic, and at int.MaxValue + 1 in C#?
Visual Basic throws OverflowException, because it checks integer arithmetic unless the project turns that off. C# wraps to -2147483648 unless the code or the project asks for checked arithmetic.
From the lesson VB.NET for C# developers: the differences
-
A procedure has Handles Button1.Click and Form_Load also adds it with AddHandler. What happens on a click?
It runs twice, once per wiring. Keep Handles for controls the designer made and AddHandler for objects created while the program runs, one wiring per handler.
From the lesson VB.NET for C# developers: the differences
-
Option Compare Text is the first line of a file. What is "Pune" = "PUNE" there?
True: in that file, Visual Basic's own string operators ignore case and follow the current culture. String.Equals is a .NET method, so it still tells the two apart.
From the lesson VB.NET for C# developers: the differences
-
What does a Visual Basic query that starts with Aggregate … Into Sum(…) return?
A single value, not a sequence: 2960 cents for the lesson's five orders. C# query syntax has no such keyword, so a port calls .Sum(…).
From the lesson VB.NET LINQ, XML literals and Async
-
Which Visual Basic query clauses does C# write as method calls instead?
Aggregate … Into, Group By … Into with named aggregates, Skip While, Take While and Distinct. Both languages reach the same standard LINQ query operators.
From the lesson VB.NET LINQ, XML literals and Async
-
Is an XML literal in Visual Basic a string?
No: the compiler turns it into XElement objects of LINQ to XML, which you can query, change and save. <%= … %> puts the value of an expression in as content or as an attribute.
From the lesson VB.NET LINQ, XML literals and Async
-
An embedded expression in an XML literal holds Bose & Sons. What reaches the document?
Escaped text, Bose & Sons: a value can never add elements or break the markup. The attribute axis .@name reads it back as plain Bose & Sons.
From the lesson VB.NET LINQ, XML literals and Async
-
What do .<customer>, .@name, ...<item> and (1) reach in Visual Basic's XML axis properties?
The customer child elements, the name attribute, item elements at any depth, and the second element of a sequence, as the index counts from 0. What they return is text until you convert it.
From the lesson VB.NET LINQ, XML literals and Async
-
How should a .NET program read XML that comes from outside, such as a supplier's file?
Through an XmlReader created with DtdProcessing.Prohibit and no resolver, which refuses any document with a DTD. Keep a test that a <!DOCTYPE is refused.
From the lesson VB.NET LINQ, XML literals and Async
-
Where does Visual Basic refuse an Await that C# accepts?
Inside a Catch or a Finally block, with error BC36943. Note the failure in the Catch and await after End Try.
From the lesson VB.NET LINQ, XML literals and Async
-
Why does a Visual Basic console program end its Main with GetAwaiter().GetResult()?
Main cannot be Async in Visual Basic: the compiler answers BC30737, no suitable Main. So Main waits for its first task itself.
From the lesson VB.NET LINQ, XML literals and Async
-
What is a characterisation test?
A test that calls existing code with chosen inputs and takes its present answers as the expected values, odd ones and bugs included, so that a refactoring or a port can prove it changed nothing.
From the lesson Project: port a VB.NET module to C#
-
The legacy Split(-10, 3) gives -3, -3 and -3 and loses a paisa. What should the port return?
The same -3, -3, -3, which the characterisation test records. Fixing it changes what customers see, so that is a separate decision with a test of its own.
From the lesson Project: port a VB.NET module to C#
-
Why can a Visual Basic module be ported to C# one piece at a time?
A solution may mix C# and Visual Basic projects that reference one another, so the old module, its port, the tests and the application all build together while the calls move over.
From the lesson Project: port a VB.NET module to C#
-
Which solution file does dotnet new sln write with the .NET 10 SDK?
An .slnx file, the XML solution format, which is now the default. From SDK 9.0.200 on, --format sln chooses the older text format for tools that cannot read slnx.
From the lesson Project: port a VB.NET module to C#
-
Why did the line-by-line C# port turn NextCode("0041") into "00411"?
With Option Strict Off, Visual Basic's + adds when the string holds a number, giving 0042 once formatted; C#'s + joins strings. The port parses the number, adds 1 and formats the result with 0000.
From the lesson Project: port a VB.NET module to C#
-
Why did Tax(1025, 18) pass even in the wrong first port?
By chance: 184.5 rounded to even is 184, and integer division also drops the half to 184. Test cases belong where rules part ways, around halves and signs.
From the lesson Project: port a VB.NET module to C#
-
Where do a port's expected values come from?
From the legacy module, asked by the runner case by case. Values worked out from the port's own logic agree with it by construction and hide every change of behaviour.
From the lesson Project: port a VB.NET module to C#
-
In which order does an application move from the Visual Basic module to its C# port?
One call site at a time, with every release covered by the same cases, and the legacy module is deleted last, when nothing calls it any more.
From the lesson Project: port a VB.NET module to C#
-
A Free Pascal program adds 1 to 2,147,483,647 with its checks left at their defaults. What does it print?
−2,147,483,648, and nothing stops it: range and overflow checks stay off until you switch them on.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
Which fpc.cfg does the compiler read, and how can you see where it looked?
The first one it finds, on a Mac ~/.fpc.cfg in the home folder before the etc folder above the compiler's bin folder. A build with -vt lists every place it tried.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
In Free Pascal's default fpc mode, how big is an Integer and what is a string?
An Integer has 16 bits, so High(Integer) is 32,767, and string means ShortString, which holds up to 255 characters. class is not a keyword there: objfpc mode brings classes, exceptions and interfaces.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
How is a generic record written in objfpc mode, and in delphi mode?
objfpc: generic TPair<T> = record, used as specialize TPair<Integer>. delphi: TPair<T> = record, with neither keyword, as Delphi code writes it.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
Why must {$H+} come after {$mode objfpc} and not before it?
A mode directive sets {$H} as well, and objfpc turns it off. A {$H+} written first is undone, and string quietly stays a ShortString.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
A file starts with {$mode objfpc} and {$R-} and is built with fpc -Mdelphi -Sh -Cr. Which settings win?
The file's: objfpc mode, ShortStrings and range checks off. The compiler reads fpc.cfg, then the command line, then the directives in the file, and a later setting replaces an earlier one.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
On a 64-bit CPU, which check stops High(Integer) + 1 from being stored in an Integer?
Range checking, {$R+} or -Cr. The sum is worked out in 64 bits, where it does not overflow, and only storing it in 32 bits goes wrong, so {$Q+} alone lets it through.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
How do Delphi, Free Pascal and Lazarus relate?
Delphi is Embarcadero's commercial IDE and compiler. Free Pascal is an open-source compiler that also reads Delphi syntax, and Lazarus is an open-source IDE built on Free Pascal. All three use Object Pascal.
From the lesson Object Pascal setup: FPC, modes and Delphi
-
What do the interface and implementation sections of a Pascal unit hold?
The interface lists what other code may use, like a C header; the implementation holds the code and what stays private. A routine declared only in the implementation does not exist outside the unit.
From the lesson Object Pascal for Python and C developers
-
A program uses Grades and then Tally, and Grades itself uses Tally. Which unit starts first?
Tally. The units a unit depends on start before it, and apart from that the uses clause sets the order; finalization runs the other way round.
From the lesson Object Pascal for Python and C developers
-
What happens when 9 is stored in a variable of the subrange type 1..8?
With range checks on, {$R+}, that store raises ERangeError on the spot. Without them, 9 is stored and nothing notices.
From the lesson Object Pascal for Python and C developers
-
What are -7 div 2 and -7 mod 2 in Object Pascal, and the same sums in Python?
−3 and −1 in Pascal, which cuts towards zero as C does; −4 and 1 in Python, whose // rounds down and whose % takes the divisor's sign.
From the lesson Object Pascal for Python and C developers
-
What does WriteLn(7 / 2) print in Free Pascal, and how do you print 3.50?
3.5000000000000000E+000, because / always gives a real and reals are written in scientific notation without a format. WriteLn(7 / 2:0:2) prints 3.50.
From the lesson Object Pascal for Python and C developers
-
What is Length('café') for an AnsiString read from a UTF-8 source file?
5, because an AnsiString holds bytes and é takes two, 195 and 169. Python's len counts characters and gives 4.
From the lesson Object Pascal for Python and C developers
-
With s = 'Pascal', what do Copy(s, 0, 3) and Pos('', s) return?
Pas, since Copy reads position 0 as 1, and 0, since an empty string counts as not found. Positions start at 1, so 0 always means a miss.
From the lesson Object Pascal for Python and C developers
-
What may a routine do with a var, a const and an out parameter?
var is another name for the caller's variable; const may not be assigned at all; out reaches the caller's variable too, but its old value is thrown away. A plain parameter is a copy.
From the lesson Object Pascal for Python and C developers
-
Who frees an Object Pascal class instance?
Your own code: a class variable points to an object on the heap, and nothing frees it until Free runs its destructor. leak.pas, which never did, ended with one 24-byte block unfreed.
From the lesson Pascal classes, generics and exceptions
-
Why is s := TStudent.Create(…) written before try, not inside it?
If the constructor fails, the destructor runs by itself and s is never assigned, so a Free in finally would act on garbage. Created first, the object exists whenever try is entered.
From the lesson Pascal classes, generics and exceptions
-
What does the build option -gh add to a Free Pascal program?
The heaptrc unit: it records every allocation and, at exit, reports the blocks that were never freed, such as 1 unfreed memory blocks : 24.
From the lesson Pascal classes, generics and exceptions
-
What does a list created with TObjectList.Create(True) do with the objects put in it?
It owns them: freeing the list frees each of them too, so the program frees only the list.
From the lesson Pascal classes, generics and exceptions
-
Given property Marks: Integer read FMarks write SetMarks, what runs for s.Marks := 191?
A call to SetMarks(191), which can refuse the value by raising. Reading s.Marks reads FMarks directly, and a property with no write cannot be assigned at all.
From the lesson Pascal classes, generics and exceptions
-
In which order do except handlers for EBadMarks and its parent EMarksError go?
The child first. Handlers are tried top to bottom and the first one whose class matches wins, so a parent placed first would catch its children as well.
From the lesson Pascal classes, generics and exceptions
-
What happens when a Free Pascal exception reaches no handler at all?
SysUtils' default handler reports that an unhandled exception occurred, with the class and the message, and ends the program with exit status 217.
From the lesson Pascal classes, generics and exceptions
-
Why must you never call Free on an object still held by a COM-style interface variable?
The interface references are counted, and releasing the last one frees the object a second time; in the lesson that stopped with EInvalidPointer. Give each object one owner: the count, or {$interfaces corba} and your own Free.
From the lesson Pascal classes, generics and exceptions
-
Why is the student's name the last column of the marks report?
Format pads to a width counted in bytes, so a name with a two-byte letter, such as Zoë, would knock a later column out of line. In the last column it needs no padding.
From the lesson Project: a marks report in Object Pascal
-
Which marks does TryStrToInt accept that a marks file must refuse?
A leading space, a plus sign and $5A, which Pascal reads as hexadecimal 90. The reader therefore checks for one to three decimal digits before it converts.
From the lesson Project: a marks report in Object Pascal
-
Written with two decimals, 2.675 prints as what in Free Pascal and in Python?
2.68 in Free Pascal and 2.67 in Python. The binary value stored for 2.675 is slightly smaller than 2.675, and each language rounds it by its own rule.
From the lesson Project: a marks report in Object Pascal
-
How does the marks report keep every percentage exact?
As whole hundredths: the total out of 500 times 20, so 453 marks are 9,060 hundredths, printed 90.60. No real number appears anywhere in the statistics.
From the lesson Project: a marks report in Object Pascal
-
How do you round a ÷ b half up using whole numbers only?
(2 * a + b) div (2 * b). Case 09's mean, 10,020 ÷ 8 = 1,252.5, becomes (20,040 + 8) div 16 = 1,253, printed 12.53.
From the lesson Project: a marks report in Object Pascal
-
What does the marks report do with a bad line, and what does exit status 2 tell a script?
It writes line N: reason to standard error, nothing to standard output, and exits with 2: no report was made. A bug, an exception nobody handled, ends with 217 instead.
From the lesson Project: a marks report in Object Pascal
-
Why is Halt(2) called only in the main program of the marks report?
Halt skips any try … finally blocks that are still open. When the exception has reached the main program, those blocks have all run, so stopping there is safe.
From the lesson Project: a marks report in Object Pascal
-
What do the 11 fpcunit tests and the 32 black-box cases of the marks project each pin down?
The unit tests pin single functions, such as the half-up mean, and name the one that broke. The cases pin what a user sees, the output, the errors and the exit status, however the code inside is written.
From the lesson Project: a marks report in Object Pascal
-
How do you pin the compiler and the build tool that Alire uses?
alr toolchain --select gnat_native=16.1.0 gprbuild=26.0.1. GNAT and GPRbuild are crates of Alire's index, so they install into Alire's own folder instead of the system.
From the lesson Ada with Alire and GNAT 16: install and build
-
Which files of an Alire crate do you edit, and which one does alr rewrite?
You edit alire.toml and the crate's .gpr project file. alr writes the config/ folder afresh on every build, with the switches of the current profile, so changes there are lost.
From the lesson Ada with Alire and GNAT 16: install and build
-
Which Alire build profile turns on assertions and contracts?
Only validation: it adds -gnata, and also -gnatwe, which makes every warning and style message an error. The development and release profiles leave contracts unchecked.
From the lesson Ada with Alire and GNAT 16: install and build
-
In which profile does a plain alr build compile your crate, and its dependencies?
Your crate in development, unless you pass --validation or --release; the crates it depends on in release.
From the lesson Ada with Alire and GNAT 16: install and build
-
Why does GNAT's style check ask for and then in a condition built from two comparisons?
Rule -gnatyB allows plain and and or only for modular or array operands and simple Boolean variables or constants. Comparisons joined in a condition take the short-circuit form.
From the lesson Ada with Alire and GNAT 16: install and build
-
Which Ada edition does GNAT 16.1.0 compile by default, and how does a crate move to Ada 2022?
Ada 2012. Two lines in alire.toml, a [build-switches] table with "*".ada_version = "Ada2022", make Alire add -gnat2022 to every profile.
From the lesson Ada with Alire and GNAT 16: install and build
-
Does a program built with GNAT have to be released under the GPL?
No. The run-time library it links carries the GCC Runtime Library Exception 3.1, so code compiled with GNAT may be passed on under terms of your choice.
From the lesson Ada with Alire and GNAT 16: install and build
-
A validation build fails on style messages. Why is switching the style checks off the wrong fix?
It keeps every slip in the code. Each message gives its line, its column and the switch behind it, and that switch's entry in the GNAT User's Guide says exactly what it wants.
From the lesson Ada with Alire and GNAT 16: install and build
-
What does type Mark is range 0 .. 100; give you that a C typedef does not?
A new type, not a synonym: mixing a Mark with another integer type needs a conversion or the code does not compile, and storing 101 in a Mark raises Constraint_Error.
From the lesson Ada for C and Java developers: strong types
-
A Mark of 98 gets 5 grace marks. Where does Ada's range check stop it?
Only when 103 is stored in a Mark. The sum itself is computed in Mark'Base, −128 .. 127 with GNAT here, so printing it with Mark'Image showed 103.
From the lesson Ada for C and Java developers: strong types
-
What are -7 / 2, -7 rem 2 and -7 mod 2 in Ada?
−3, −1 and 1. As in C and Java, / and rem truncate; mod follows the sign of the divisor, as Java's Math.floorMod does.
From the lesson Ada for C and Java developers: strong types
-
What does Integer'Last + 1 do in Ada, in Java and in C?
Ada raises Constraint_Error, because GNAT checks overflow by default; Java silently wraps to −2,147,483,648; C leaves it undefined.
From the lesson Ada for C and Java developers: strong types
-
How does Ada code read an array's bounds, and what happens at an index past the end?
With 'First, 'Last, 'Length and 'Range, as in for I in Class'Range loop, so no separate count is needed. Class (5) on an array indexed 1 .. 4 stopped with index check failed.
From the lesson Ada for C and Java developers: strong types
-
Why did Class'Reduce ("+", 0) fail on the marks 72 and 95?
Its accumulator is a Mark, since it uses the "+" of Mark, and 72 + 95 = 167 is outside Mark'Base. Converting each mark to Natural first gave the total of all four, 253.
From the lesson Ada for C and Java developers: strong types
-
What do the parameter modes in, out and in out let a procedure do with a value?
in: only read it, and an assignment to it does not compile. out: hand a result back. in out: read it and write it. The mode is part of the specification a caller sees.
From the lesson Ada for C and Java developers: strong types
-
How do an Ada package's specification and body divide the work?
The specification, a .ads file, lists everything callers may use; the body, a .adb file, holds the code. Callers depend on the specification alone.
From the lesson Ada for C and Java developers: strong types
-
Why did the call With_Gst (-5, 18) print −5 in one build and fail in the next, with no line changed?
Pre and Post are checked only with assertions enabled, -gnata, which the validation build adds. The development build ignored the precondition and ran the body.
From the lesson Ada contracts, tasks and a first SPARK proof
-
Name three ways to make GNAT check a crate's contracts.
Build with alr build --validation; set "*".contracts = "Yes" under [build-switches] in alire.toml; or write pragma Assertion_Policy (Check); in the code.
From the lesson Ada contracts, tasks and a first SPARK proof
-
When a precondition fails, and when a postcondition fails, whose mistake is it?
A failed Pre is the caller's: the call broke what the subprogram needs. A failed Post is the body's: it broke what the subprogram promised to return.
From the lesson Ada contracts, tasks and a first SPARK proof
-
How do a loop and a membership test treat a subtype with a predicate?
for Day in Exam_Day visits only the values a static predicate allows, MON, WED and FRI. S in Even_Seat just answers FALSE for 7, while storing 7 in such a variable raises Assertion_Error.
From the lesson Ada contracts, tasks and a first SPARK proof
-
When does Ada check a Type_Invariant?
When an operation visible outside the type's package returns, so the wallet's negative balance was caught only as Pay came back. A precondition stops the same call before the body runs.
From the lesson Ada contracts, tasks and a first SPARK proof
-
How do three Ada tasks share one counter without losing an update?
The counter lives in a protected object, whose procedures run one at a time while its functions may read together. Every run of the lesson's program printed 1,400,000.
From the lesson Ada contracts, tasks and a first SPARK proof
-
What does the barrier when Done = 3 on a protected entry do?
It holds calls to the entry in a queue until Done = 3 is True, and the queue is looked at again after each protected procedure, so the waiting task never polls.
From the lesson Ada contracts, tasks and a first SPARK proof
-
Why could GNATprove not first prove that Sum + Natural (List (I)) never overflows?
Without a loop invariant it knew only that Sum is a Natural after any number of passes. Adding Sum <= 100 * (I - List'First + 1) bounded it, and all 9 checks were proved.
From the lesson Ada contracts, tasks and a first SPARK proof
-
When may the crossing controller lift the barriers?
Only when its count of trains that have approached and not yet left is back to 0. A second train that is still expected keeps them down when the first one leaves.
From the lesson Project: a level-crossing controller in Ada
-
What makes the crossing controller fail-safe?
Every event that contradicts the mode, a sensor fault, a clock going back, a fourth train, leads to fault: barriers down, lights flashing, bell ringing. Fault is never left.
From the lesson Project: a level-crossing controller in Ada
-
Why are the controller's barriers, lights and bell expression functions of the mode?
So the outputs can never disagree with the mode: there is no variable anywhere that could say the barriers are up while a train is expected.
From the lesson Project: a level-crossing controller in Ada
-
What does (S with delta Last => Now) build?
An Ada 2022 delta aggregate: a copy of the record S in which only the component Last is changed, to Now.
From the lesson Project: a level-crossing controller in Ada
-
A seeded bug opens the crossing on every leave. Why did five of the six scenarios still pass?
None of them had two trains at once, and with one train, opening on every leave is right. Only the scenario with a second train approaching broke the counting rule.
From the lesson Project: a level-crossing controller in Ada
-
How does each scenario test of the controller decide pass or fail?
The program writes actual.log beside the scenario's expected.log, and cmp -s compares the two byte for byte. It says only whether they are equal.
From the lesson Project: a level-crossing controller in Ada
-
Why is GNATprove run here with --steps=1000 rather than with a timeout?
A step limit gives the same result on every machine; a timeout depends on the machine and its load. The default limit, 100 steps, left one check unproved, and 1,000 proved all 35.
From the lesson Project: a level-crossing controller in Ada
-
What did GNATprove report for the seeded bug, with no scenario at all?
An unproved counting clause in the postcondition of Next, the same rule the two-train scenario broke, and --checks-as-errors=on failed the command. A proof covers every mode, count, time and event.
From the lesson Project: a level-crossing controller in Ada
-
How do you see which Tcl a command starts, and what did a Mac's own /usr/bin/tclsh answer?
Pipe puts [info patchlevel] into it, as in echo 'puts [info patchlevel]' | tclsh9.0, which prints the full version, here the pin 9.0.4. macOS's /usr/bin/tclsh answered 8.5.9.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
What does argv hold when tclsh runs a script?
The words that follow the file name, as a list: tclsh9.0 hello.tcl fast verbose gives argv the 2 words fast and verbose.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
Are if, while and proc keywords in Tcl?
No, they are commands. The first word of every command names it, and each command decides what its remaining words mean, scripts included.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
What do string length and expr make of the value 042 on Tcl 9?
3 for string length, which reads characters, and the number 42 for expr, which added 1 and printed 43. Every value is a string that each command reads the way it needs.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
Why is text from a file passed through split before list commands read it?
Text such as clk_core {io 10 is a fine string but a broken list: llength stopped with unmatched open brace in list, while split made 3 items of it.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
What does string length return for the emoji U+1F600 on Tcl 8.5.9 and on Tcl 9.0.4?
4 on 8.5.9, which counted the four UTF-8 bytes as characters, and 1 on 9.0.4, which handles every Unicode code point as one character.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
Inside namespace eval report, a script runs set units ns. What does that change on Tcl 8.5.9, and on Tcl 9.0?
The global units on 8.5.9; a new report::units on 9.0, where the global keeps its value. Write set ::units for the global and variable units for the namespace's own.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
How does a script that calls Tcl 9.1 commands stop cleanly on Tcl 9.0?
With package require Tcl 9.1 as its first line: 9.0.4 refused with have 9.0.4, need 9.1 before any output. package vsatisfies asks the same question without failing.
From the lesson Tcl 9.0 and 9.1: install and what changed
-
What do double quotes, braces and brackets do with $name and [cmd] inside them?
Double quotes substitute both; braces leave both as text; brackets run their script first and put its result where they stood.
From the lesson Tcl for Python and Bash users: the rules
-
$name holds two words. How many arguments does count_words $name receive in Tcl, and in Bash?
One in Tcl, where a substitution never changes word boundaries; two in Bash, which splits an unquoted expansion at IFS. Tcl splits only on request, with {*}$name.
From the lesson Tcl for Python and Bash users: the rules
-
Why does a list built with lappend count 3 items where the same items joined with spaces count 4?
lappend quotes an item that holds a space, writing {scan enable}; text glued together with spaces marks nothing, so that item falls apart into two.
From the lesson Tcl for Python and Bash users: the rules
-
How do dict get and dict getwithdefault treat a key that is missing?
dict get raises key "E999" not known in dictionary; dict getwithdefault, new in Tcl 9.0, returns the default you give, such as 0.
From the lesson Tcl for Python and Bash users: the rules
-
Why is every Tcl expression written inside braces?
expr substitutes its argument itself. In braces each variable is read once and stays data; without them a value holding [incr calls] ran as a command. Braced expressions also compile to bytecode.
From the lesson Tcl for Python and Bash users: the rules
-
Which arguments does Tcl's exec treat as redirections or control, not as data?
Any that starts with <, >, | or 2>, and a last argument of &. Write a relative file name from outside as ./name, or refuse such names before calling exec.
From the lesson Tcl for Python and Bash users: the rules
-
How does a trap clause of try match an error, and why do traps come before on error?
trap matches when its pattern is a prefix of the -errorcode list. The first matching clause wins, so an on error placed earlier would take every error.
From the lesson Tcl for Python and Bash users: the rules
-
add_violation links its first argument with upvar. Why does add_violation $tns -10 leave tns unchanged?
upvar needs the variable's name. Given $tns, it linked a variable named after the value, -170, in the caller; the call must be add_violation tns -10.
From the lesson Tcl for Python and Bash users: the rules
-
A script schedules after 100 {puts tick} and reaches its end. Why is tick never printed?
Delayed scripts run only inside the event loop, and tclsh leaves at the end of the script. vwait done enters the loop and stays there until a callback sets done.
From the lesson Tcl event loop, coroutines and small DSLs
-
In which order did ticker.tcl's after 0, after idle and timed callbacks run?
after 0 first, due as soon as the loop started; then the idle callback, with nothing else due; then the timers by their times, the two at 100 ms in the order they were scheduled.
From the lesson Tcl event loop, coroutines and small DSLs
-
Why should a callback never call vwait itself?
Because waits nest, the outer vwait cannot return before the inner one has, and an inner wait whose variable is never set keeps both stuck. Keep the only wait at the top of the program.
From the lesson Tcl event loop, coroutines and small DSLs
-
What does coroutine next_net gen do?
It makes a command next_net and runs gen up to its first yield, returning the yielded value. Every call of next_net resumes gen to its next yield, and the command disappears when gen returns.
From the lesson Tcl event loop, coroutines and small DSLs
-
Where may yield appear in a Tcl coroutine, compared with a Python generator?
In any procedure the coroutine calls, so a helper can yield on its behalf. In Python a helper containing yield becomes a generator itself and needs yield from.
From the lesson Tcl event loop, coroutines and small DSLs
-
How long does a TclOO object live?
Until destroy removes it: an object is a command, not something collected when the last reference goes. Its variables stay private behind the exported, lower-case methods.
From the lesson Tcl event loop, coroutines and small DSLs
-
What does interp create -safe hide, and how does the loader give a file back the words of its language?
It hides commands such as exec, file, open, socket and source. interp alias adds back only the language's words, each running a checking procedure in the main interpreter.
From the lesson Tcl event loop, coroutines and small DSLs
-
Why does the safe interpreter need a time limit as well as a command limit?
A loop with an empty body counts no commands inside it, so only the time limit stopped spin.tcl; loop.tcl stopped at the 1,000-command limit.
From the lesson Tcl event loop, coroutines and small DSLs
-
What is the slack of a timing path, and what does a negative one mean?
Required time minus arrival time. A negative slack means the signal arrives too late, so the path fails timing.
From the lesson Project: a timing-report summariser in Tcl
-
How does the summariser define a clock's worst slack and total negative slack?
Worst slack: the smallest slack of its paths, even when positive. Total negative slack: the sum of the negative slacks, 0 if none fails. core's were −0.160 and −0.215 ns.
From the lesson Project: a timing-report summariser in Tcl
-
How does the parser check that a field line holds exactly two words?
scan $text {%s %s %s} key value extra returns how many words it filled: 2 is a field, 3 means text after the value, and 1 a value that is missing.
From the lesson Project: a timing-report summariser in Tcl
-
Why is scan's %n no safe way to find the end of a line on Tcl 9.0.4?
It counted UTF-8 bytes, 22 for a 21-character line holding mémoire. A check built on it passes every ASCII report and refuses names with letters such as é.
From the lesson Project: a timing-report summariser in Tcl
-
Why are all times turned into whole picoseconds as soon as they are read?
A time of at most three decimals in ns is a whole number of ps, so every sum after that is exact. As reals, −0.120 + −0.050 printed −0.16999999999999998.
From the lesson Project: a timing-report summariser in Tcl
-
How does the summariser order its rows by worst slack, with ties by clock name?
It sorts twice, first by name and then by worst slack. lsort is a stable merge sort, so rows with equal worst slack keep the name order of the first sort.
From the lesson Project: a timing-report summariser in Tcl
-
How does the summariser name the line that holds a byte which is not UTF-8?
Its strict UTF-8 read raises EILSEQ and returns the text decoded before the bad byte in -data. Counting the lines of that text gave line 4 for bad_bytes.txt.
From the lesson Project: a timing-report summariser in Tcl
-
Why does the speed test time the fastest of three runs over 10,000 paths?
So that a brief burst of other work on the same computer cannot fail the test. The budget is under 1 s to parse and summarise them.
From the lesson Project: a timing-report summariser in Tcl
-
Which three commands report the versions behind an Objective-C build on a Mac?
pkgutil --pkg-info=com.apple.pkg.CLTools_Executables for the Command Line Tools, clang --version for the compiler, Apple clang 21.0.0 here, and xcrun --show-sdk-version for the SDK, 27.0.
From the lesson Objective-C with clang and Foundation on macOS
-
What do the two messages of [[Price alloc] init] do?
alloc reserves a zeroed Price object, and init sets it up. Every pair of square brackets is a message send.
From the lesson Objective-C with clang and Foundation on macOS
-
What does @property (nonatomic) long long paise; give a class?
Storage and two accessors the compiler writes for you, paise and setPaise:. mrp.paise = 5 and [mrp setPaise:5] both call that setter.
From the lesson Objective-C with clang and Foundation on macOS
-
Why did hello.m print Refund: 0.-5 rupees for −5 paise?
Objective-C keeps C's arithmetic: -5 / 100 is 0 and -5 % 100 is −5, because integer division truncates. A formatter for money has to deal with the sign itself.
From the lesson Objective-C with clang and Foundation on macOS
-
How does clang compile an Objective-C file when neither -fobjc-arc nor -fno-objc-arc is given?
With manual reference counting, so objects the code never releases leak without any warning: 0 of 3 were freed. When both flags appear, the last one wins.
From the lesson Objective-C with clang and Foundation on macOS
-
Why does every build in the Objective-C mini-course name -framework Foundation?
Linking object files without it failed with Undefined symbols for NSObject, NSString and objc_msgSend. Only the one-step build with -fobjc-arc picked Foundation up by itself.
From the lesson Objective-C with clang and Foundation on macOS
-
Where does NSLog write, and why do the atlas examples print with printf?
NSLog writes to standard error and adds the date, the time, the program and process and thread numbers, which change every run. printf and puts write only the text to standard output, so it can be compared.
From the lesson Objective-C with clang and Foundation on macOS
-
How much of the macOS SDK still declares Objective-C classes?
157 of its 332 frameworks, Foundation and AppKit among them. 93 newer ones, such as SwiftData, ship only a Swift module, and Swift code calls the Objective-C classes of the rest.
From the lesson Objective-C with clang and Foundation on macOS
-
What does a message sent to nil return?
A zero value, and nothing runs: nil for an object, 0 for a number, NO for a BOOL. That is how a missing customer's balance added 0 and the total came out as 50,000 paise.
From the lesson Objective-C for Swift and C developers
-
What is the selector of [account withdraw:20000 error:&error]?
withdraw:error:, the whole name with a colon for each argument. The keywords are part of the name, not named arguments, so the arguments always come in the declared order.
From the lesson Objective-C for Swift and C developers
-
Why are NSString properties declared copy rather than strong?
copy stores a copy of what the caller passed, so a mutable string changed afterwards leaves the property alone. strong keeps the very object, and changed with it in the lesson's run.
From the lesson Objective-C for Swift and C developers
-
How can a property be read-only for other files yet writable inside its own class?
readonly in the header, and readwrite again in a class extension, @interface Account (), at the top of the .m file. Outside it, an assignment fails with assignment to readonly property.
From the lesson Objective-C for Swift and C developers
-
Why does an NSArray hold @12 rather than 12?
Foundation collections hold objects only, so numbers go in boxed as NSNumber objects; the literals @42 and @(expr) create them.
From the lesson Objective-C for Swift and C developers
-
missing is nil. What do arrayWithObjects: and the literal @[ … ] do with it as the middle value?
[NSArray arrayWithObjects:@"pens", missing, @"clips", nil] gives a one-element array, since it stops at the first nil. The literal raises NSInvalidArgumentException.
From the lesson Objective-C for Swift and C developers
-
How does a caller tell that withdraw:error: failed?
From the BOOL it returns, never from the error pointer: a success leaves an earlier error untouched. A caller that does not want details passes NULL, and the method must check before writing through it.
From the lesson Objective-C for Swift and C developers
-
Why is a category method on NSString called atl_shout and not shout?
When a category method shares a name with a method of the class, or of another category, which one runs is undefined. A prefix keeps methods added to framework classes apart.
From the lesson Objective-C for Swift and C developers
-
Under ARC, when is an object freed?
As soon as its last strong reference goes. Object pointers are strong unless declared otherwise; weak references do not count and read nil once the object is gone.
From the lesson Objective-C ARC, blocks and Swift interop
-
What becomes of a new object that is stored only in a __weak variable?
It never has a strong reference, so it is freed straight away. clang warned that it will be released after assignment, and the run printed T4 created and T4 freed back to back.
From the lesson Objective-C ARC, blocks and Swift interop
-
A customer and an order hold each other strongly. Why are they never freed?
Each keeps one strong reference from the other when the program lets go, and ARC has no cycle collector. A weak reference from the order back to its customer freed both.
From the lesson Objective-C ARC, blocks and Swift interop
-
A block uses a local int discount, 10 at the time. The variable is then set to 50. What does the block see?
Still 10: a block copies the local values it uses, as constants, at the moment it is created. Only a variable marked __block is shared with the scope around it.
From the lesson Objective-C ARC, blocks and Swift interop
-
Why can a block that only uses the instance variable _label keep its object alive?
Using an instance variable captures self, so the block holds the whole object strongly although self is never written. If self stores that block, the two form a ring.
From the lesson Objective-C ARC, blocks and Swift interop
-
How should a block that self keeps refer to self?
Through __weak typeof(self) weakSelf = self;, written before the block. Inside, take a strong copy of weakSelf for one run and test it for nil, since the object may already be gone.
From the lesson Objective-C ARC, blocks and Swift interop
-
What does Swift see for an unannotated method returning NSString *, and for the same method marked nullable?
String!, an implicitly unwrapped optional, which stopped with exit status 133 on nil; and String?, which the compiler makes you unwrap. NSArray<NSString *> * comes in as [String], a plain NSArray as [Any].
From the lesson Objective-C ARC, blocks and Swift interop
-
Why is [NSString stringWithFormat:note] dangerous when note comes from outside the program?
The note becomes the format: a % swallowed text, and a note holding two %@ made it die with exit status 139 (CWE-134). Pass the note as an argument of @"%@", and build with -Werror=format-security.
From the lesson Objective-C ARC, blocks and Swift interop
-
What is a trial balance?
A list of every account's balance, debits minus credits, set out in two columns whose totals must agree. In double-entry bookkeeping each transaction's debits equal its credits.
From the lesson Project: a command-line ledger in Objective-C
-
In the ledger's report, which column takes a balance of 0, and which a negative balance?
A balance of 0 or more goes in the debit column and a negative one in the credit column, with the accounts in the order the file lists them.
From the lesson Project: a command-line ledger in Objective-C
-
Why does the ledger add paise with __builtin_add_overflow?
It reports 1 whenever the exact result overflows a long long, so no transaction total and no account balance can wrap round to a negative number, however absurd the file.
From the lesson Project: a command-line ledger in Objective-C
-
What happens when 100 rupees is split three ways with NSDecimalNumber, and in whole paise?
NSDecimalNumber rounds each share to 33.33, and the three make 99.99: a paisa vanishes. In paise, 10,000 becomes 3,334 + 3,333 + 3,333, because the code decides where the remainder goes.
From the lesson Project: a command-line ledger in Objective-C
-
Why does isKindOfClass:[NSNumber class] wrongly accept a credit of true?
Foundation reads JSON's true as an NSNumber of value 1. A whole amount must also not be a CFBoolean and not be stored as a double or float, which rules out true, 12.5 and 1.0.
From the lesson Project: a command-line ledger in Objective-C
-
Where did Foundation's JSON parser part from RFC 8259 in the lesson's run?
It accepted a trailing comma, which the RFC's grammar forbids, and kept the first value of a repeated name. A number with a leading zero it refused, as the RFC asks.
From the lesson Project: a command-line ledger in Objective-C
-
What does the ledger do with a file that has three problems?
Posts nothing, writes all three to standard error, one line each, and exits with 2. An unreadable file exits with 1, and only a clean file prints the report with status 0.
From the lesson Project: a command-line ledger in Objective-C
-
Why are ledger cases 06 and 07 characterisation tests?
They record what Foundation's parser does today, accepting trailing commas and its message for unquoted names, so a stricter parser in a later macOS would show up as a failing case.
From the lesson Project: a command-line ledger in Objective-C
-
Which JDK does Groovy 6.0 need, and which two pins does groovy --version show?
A JDK 17 or newer. Its version line names Groovy Version: 6.0.0 and the JVM it found through JAVA_HOME, 21.0.12.1 for this mini-course.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
How do you make sure a downloaded Groovy zip is the one the project published?
Compute its SHA-256 with shasum -a 256 and compare the 64 hexadecimal digits with the .sha256 file beside the download. Equal digits mean the same bytes.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
What does groovyc produce for hello.groovy, a script with no class in it?
hello.class, which extends groovy.lang.Script with a run() method holding the statements and a main method, plus a class for each closure, such as hello$_run_closure1.class.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
Why did java -cp . hello stop with NoClassDefFoundError: groovy/lang/Script?
Compiled Groovy calls Groovy's runtime library for what Java lacks. Put groovy-6.0.0.jar on the classpath beside the classes and the same program runs.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
Which Groovy compiles a Jenkinsfile?
The one inside the Jenkins controller: Jenkins core manages groovy-all 2.4.21. Neither the Groovy on your laptop nor the one on an agent is used.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
Why does findAll(s -> s !in stages) run on Groovy 6.0.0 and fail on 2.4.21?
Java-style lambdas and !in arrived with Groovy 3.0's Parrot parser, so 2.4 stops at unexpected token: ->. The closure findAll { !(it in stages) } works on both.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
Which Groovy reads a build.gradle?
The Groovy carried inside Gradle's own distribution: gradle --version reported Groovy 4.0.32 for Gradle 9.7.1, whatever Groovy is installed beside it.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
When does a project stay on Groovy 5.1 rather than move to 6.0?
When it runs on a JDK older than 17, such as JDK 11, or when its tests still use Spock 2.4: Spock 2.5 is the first with a build for Groovy 6.0.
From the lesson Groovy 6 on JDK 21, and the Groovy in Jenkins
-
What do builds.sum { it.minutes } and builds.max() return when builds is empty?
null for both, where Java's IntStream.sum() gives 0 and max() an empty Optional. builds.sum(0) { it.minutes } starts at 0, so it returns 0 for no items.
From the lesson Groovy for Java developers: idioms and traps
-
What does == compare in Groovy, and how do you ask for identity?
Values: compareTo for Comparable types and equals for others, so two equal strings built in different ways are ==. Identity is a.is(b), or a === b from Groovy 3 on.
From the lesson Groovy for Java developers: idioms and traps
-
Are the BigDecimal values 1.0 and 1.00 equal in Groovy?
== says yes, because it goes through compareTo, which ignores the scale; equals says no, because the scales differ, so a HashSet can hold both.
From the lesson Groovy for Java developers: idioms and traps
-
Which values does Groovy truth treat as false?
null, empty strings, collections and maps, the number zero and a matcher without a match. The text 'false', the text '0' and a map holding one entry are all true.
From the lesson Groovy for Java developers: idioms and traps
-
build?.minutes ?: 30 is applied to a 0-minute build. Why is the result 30?
?: falls back whenever its left side is false under Groovy truth, and 0 is false. Where 0 can be a real value, test for null instead: m != null ? m : 30.
From the lesson Groovy for Java developers: idioms and traps
-
What is 7 / 2 in Groovy, and how do you divide whole numbers the way Java does?
3.5, a BigDecimal, and an endless division keeps 10 decimals, so 2 / 3 * 3 is 2.0000000001. 7.intdiv(2) is 3 and (-7).intdiv(2) is −3, as in Java.
From the lesson Groovy for Java developers: idioms and traps
-
What does a failing Groovy power assertion print?
The expression, with the value of every evaluated part written under it. A part that never ran, such as the right side of a false &&, shows nothing.
From the lesson Groovy for Java developers: idioms and traps
-
Which members does @Canonical write into a Groovy class?
It stands for @ToString, @EqualsAndHashCode and @TupleConstructor: constructors from all properties down to none, plus toString, equals, hashCode and canEqual.
From the lesson Groovy for Java developers: idioms and traps
-
What do this, owner and delegate refer to inside a Groovy closure?
this: the class around the code. owner: the object or closure in which the closure was defined. delegate: an object anyone may set, which starts out as the owner.
From the lesson Groovy closures, DSLs and static checking
-
Both the owner and the delegate have a name. Which value does a closure get under the default strategy?
The owner's: OWNER_FIRST asks it first, so name gave release from the script's binding. Under DELEGATE_FIRST the delegate answered with test.
From the lesson Groovy closures, DSLs and static checking
-
Why does a builder set resolveStrategy to Closure.DELEGATE_FIRST as well as the delegate?
So the words of its DSL reach the spec that defines them even when the code around the block has a property or binding variable with the same name.
From the lesson Groovy closures, DSLs and static checking
-
Which name does no resolve strategy override?
A local variable declared where the closure is written: the closure captures it rather than looking it up, so it answered local even under DELEGATE_ONLY.
From the lesson Groovy closures, DSLs and static checking
-
How does a DSL block such as stage('Build') { steps { sh 'make' } } work underneath?
Each word is a method call whose last argument is a closure. The method makes the spec of the next level the closure's delegate and runs it.
From the lesson Groovy closures, DSLs and static checking
-
Why is stage 'Deploy' { … } not the same call as stage('Deploy') { … }?
Without the parentheses Groovy gives the closure to the argument, so 'Deploy' { … } turned into a call of a method named Deploy and failed. Keep the parentheses when a closure follows an argument.
From the lesson Groovy closures, DSLs and static checking
-
What does @TypeChecked do to a typo such as it.minuts?
Makes it a compile error, since names are resolved when the code compiles; dynamic Groovy failed only when the line ran. A builder's closure parameter needs @DelegatesTo so the checker knows its delegate.
From the lesson Groovy closures, DSLs and static checking
-
A method of Pricing is replaced through its metaclass at run time. Which calls see the new method?
Dynamic calls do, and gave 63. A call compiled with @CompileStatic was bound when the file compiled, so it still gave 42.
From the lesson Groovy closures, DSLs and static checking
-
When does the build report call a job flaky?
When its passed and failed results, in run order and without the cancelled runs, change at least twice. api changed three times in four runs.
From the lesson Project: a build-report tool in Groovy
-
In what order does the report list the 5 slowest builds?
Longest first, ties by job name and then by run number, so the three 23-minute builds came out as etl #3, web #18 and web #19.
From the lesson Project: a build-report tool in Groovy
-
Which classes did JsonSlurper return for 12.5, for 2147483648 and for a JSON object?
A BigDecimal, a Long, because the number is too big for an Integer, and a LazyMap, Groovy's own Map. A key that is not there reads as null.
From the lesson Project: a build-report tool in Groovy
-
Which texts that are not valid JSON did the default JsonSlurper accept?
A trailing comma in an object, a leading zero, a key named twice, keeping the last value, and two documents in one text, keeping only the first. A trailing comma in a list was refused.
From the lesson Project: a build-report tool in Groovy
-
What does the report's reader do with a bad record, and why does it not skip it?
It stops and prints build N: reason, such as build 2: api #41 appears twice, on standard error with exit status 2. A report with one build quietly missing would look complete.
From the lesson Project: a build-report tool in Groovy
-
How does the comparator of slowest move from one key to the next?
Three <=> comparisons joined by ?:. A tie gives 0, which is false under Groovy truth, so ?: goes on to the next key.
From the lesson Project: a build-report tool in Groovy
-
How does the report round an average of 1.125 minutes?
Once, with divide(count, 2, RoundingMode.HALF_UP), which gives 1.13. A plain / would keep 10 decimals and invite a second rounding later on.
From the lesson Project: a build-report tool in Groovy
-
Why did the packaged jar fail with NoClassDefFoundError: groovy/json/JsonException?
JsonSlurper is in its own module, groovy-json-6.0.0.jar, not in the core groovy-6.0.0.jar. With both jars on the classpath the report printed as the script's did.
From the lesson Project: a build-report tool in Groovy
-
Which three versions does ldc2 --version report?
Three: LDC 1.43.0 itself, the pin; the front end of DMD v2.113.0, with which it reads D; and LLVM 22.1.8, which makes the machine code. A program's __VERSION__ reports 2113.
From the lesson D: compilers, dub and where D is used
-
What does ldc2 -run hello.d leave in the folder?
Nothing new: it compiles, links and runs the program in one step and then deletes it. A plain ldc2 hello.d leaves hello.o and a 1,188,488-byte program, mostly druntime and Phobos.
From the lesson D: compilers, dub and where D is used
-
A wrong unittest sits in source/app.d. Why does dub test still report success?
dub's test build brings its own main and leaves out the file holding yours, unittest blocks and all. Moved into a module, the same test failed with an AssertError.
From the lesson D: compilers, dub and where D is used
-
What are dub's debug and release build types?
debug is the default. release, chosen with dub build --build=release, means release mode with optimisation and inlining. dub test builds the unittest type and runs the tests.
From the lesson D: compilers, dub and where D is used
-
What do DMD, LDC and GDC have in common, and where do they differ?
They share the front end that reads and checks D, and with it the language version. The back end differs: DMD's own, LLVM behind LDC and GCC behind GDC.
From the lesson D: compilers, dub and where D is used
-
Which D compiler suits a Mac with Apple silicon, and why?
LDC: DMD's download page offers builds for i386 and amd64 only. On x86-64, DMD suits quick builds while editing and LDC or GDC the optimised release.
From the lesson D: compilers, dub and where D is used
-
What is ldmd2 for?
It accepts DMD's options and runs ldc2 with LDC's, so a build script written for DMD works with LDC; with -vdmd it shows that -inline turned into -enable-inlining.
From the lesson D: compilers, dub and where D is used
-
What is druntime, and how does it relate to Phobos?
The D runtime: the garbage collector, the start-up code that calls main, and core.stdc, D's declarations of the C library. Phobos, the standard library, is built on top of it.
From the lesson D: compilers, dub and where D is used
-
After s = arr[1 .. 4] in D, what does s[0] = 20 change?
arr[1] too: a slice is a pointer into the array's memory plus a length, and nothing is copied. arr[1 .. 4].dup gives a copy with memory of its own.
From the lesson D for C, C++ and Python developers
-
When does appending to a D slice make it stop sharing memory with its array?
When it cannot grow in place, for example with capacity 0 because the array goes on after it: the runtime copies the slice before appending. The code does not show this, so take .dup when you mean a copy.
From the lesson D for C, C++ and Python developers
-
small[5] is read from a three-element D array. What happens, and can catch (Exception e) handle it?
It stops with ArrayIndexError, naming index 5 and length 3. That is an Error, not an Exception, which the documentation calls unsafe to catch: fix the code instead.
From the lesson D for C, C++ and Python developers
-
What do length, walkLength and byGrapheme count for the flag 🇮🇳 in D?
8 UTF-8 code units, 2 code points and 1 character as a reader sees it. A string is an array of code units, so a slice can cut a letter in half.
From the lesson D for C, C++ and Python developers
-
What are -7 / 2, -7 % 2 and int.max + 1 in D?
−3, −1 and −2,147,483,648. Division truncates and the remainder keeps the dividend's sign, as in C, and the wrap is defined by the specification; core.checkedint can report it.
From the lesson D for C, C++ and Python developers
-
writeln prints 0.3 for 0.1 + 0.2, yet the sum compares unequal to 0.3. Why?
writeln shows a double with six significant digits. Printed with %.17g, the sum is 0.30000000000000004.
From the lesson D for C, C++ and Python developers
-
What does it mean that iota(1, 11).filter!(…).map!(…) is lazy?
Nothing is computed until a value is taken. A map over a billion numbers was built at once, and take(2) ran the squaring function exactly twice.
From the lesson D for C, C++ and Python developers
-
In a --release build, which array reads still have their bounds checked?
Only reads in @safe functions. The @system read past the end printed 61 and carried on; the @safe one still stopped with ArrayIndexError.
From the lesson D for C, C++ and Python developers
-
What does enum fib50 = fib(50); make the D compiler do?
Run the ordinary function fib during the build, so the program contains 12,586,269,025 from the start. This is compile-time function evaluation.
From the lesson D at compile time: CTFE, templates, mixins
-
Name four places where D runs a function while compiling.
The initialiser of an enum constant or of a global or static variable, static assert, static if and static foreach; template value arguments, mixins and static array sizes too.
From the lesson D at compile time: CTFE, templates, mixins
-
Which functions can D's compile-time interpreter not run?
Functions whose D source it lacks, such as the C function getenv, code that reads or writes mutable global or static state, and inline assembly. It interprets, so heavy work stays at run time.
From the lesson D at compile time: CTFE, templates, mixins
-
When does pragma(msg) print its text?
During the build: compiling ctfe.d printed 12586269025LU, the constant with a ulong suffix. The program itself prints nothing for it.
From the lesson D at compile time: CTFE, templates, mixins
-
What does adding if (isNumeric!T) to total change for a call with an array of strings?
The call itself is refused, at its own line, naming the constraint that failed. Without it, the compiler builds total!string and reports errors from inside its body.
From the lesson D at compile time: CTFE, templates, mixins
-
How does Quantity!(m, s) keep metres from being added to seconds?
Its + accepts only a Quantity of the same type, so Metres + Seconds matches no opBinary and does not compile. * and / return a type whose exponents are added or subtracted.
From the lesson D at compile time: CTFE, templates, mixins
-
Why is __traits(allMembers, Reading) the wrong list for writing CSV columns?
It lists every member, methods such as fahrenheit included. FieldNameTuple!Reading from std.traits lists the fields alone.
From the lesson D at compile time: CTFE, templates, mixins
-
What does a -betterC build give up, and what does it keep?
It drops druntime: the garbage collector and with it appends, exceptions, classes made with new, and most of Phobos, writeln included. Most of the language stays, compile-time evaluation and bounds checks too.
From the lesson D at compile time: CTFE, templates, mixins
-
What does csvstats print for a column of numbers, and for one without?
count, mean, median, min, max and the cells it skipped, with two decimals on the four values. A column with no numbers prints no numbers and how many cells it skipped.
From the lesson Project: a CSV statistics tool in D
-
Why does csvstats skip the cell " 23.0" in the celsius column?
A cell counts only if, exactly as written, it matches the number rule, and a leading space is not part of a number. Python's float() would have taken it as 23.0.
From the lesson Project: a CSV statistics tool in D
-
Which exit statuses does csvstats use?
2 when no file is named or a record has another number of cells than the header, 1 when the file cannot be read, each with a message on standard error; 0 with the report.
From the lesson Project: a CSV statistics tool in D
-
Which cells does D's to!double accept that the csvstats rule skips?
1_000, nan and 0x1Ap0. It refuses padded cells, Infinity, Devanagari digits and 1e400, all of which Python's float() accepts, so neither parser can be the specification.
From the lesson Project: a CSV statistics tool in D
-
Why does csvstats convert a cell such as 0.045 with C's strtod and not with to!double?
strtod gives the nearest double, just under the tie, which prints as 0.04, as Python's float() does. to!double gave the next double up, 0.05, and the two differed on 3,937 of 10,000 tie cells.
From the lesson Project: a CSV statistics tool in D
-
Why does csvstats print 1.00 for the cell 1.005 and 0.12 for 0.125?
It prints two decimals of the nearest double. The double for 1.005 lies just below the tie, and 0.125 is held exactly, so its half goes to the even digit. A spreadsheet rounding the text would show 1.01.
From the lesson Project: a CSV statistics tool in D
-
Where did the first reading loop, throwing.d, spend its time on 100,000 rows?
Almost all of its 2.20 s of processor time went on 200,000 exceptions, about 10.6 µs each; csvstats did the rest of the work in 0.08 s.
From the lesson Project: a CSV statistics tool in D
-
Why is the speed budget of csvstats set in processor time rather than clock time?
User plus sys time counts only the program's own work, while the clock also counts whatever else the machine does. A million rows took 0.86 s of processor time and 2.21 s on the clock.
From the lesson Project: a CSV statistics tool in D
-
Which three version pins does the Gleam mini-course check, and why three?
gleam 1.18.1, Erlang/OTP 29.1.1, read from the OTP_VERSION file of the Erlang install, and Node.js v24.21.0. Gleam brings no runtime of its own, so both targets' runtimes count.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
Which Erlang/OTP and JavaScript runtimes does Gleam 1.18 support?
Erlang/OTP 29 and 28, the two newest majors, and any JavaScript runtime with ECMAScript 2022 or later: Node.js by default, or Deno or Bun.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
What do gleam.toml and manifest.toml each record?
gleam.toml: the version ranges the project accepts. manifest.toml, written by the first build: the exact version and checksum of every package chosen. Both belong in version control.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
Why did a first gleam run without a network stop at Resolving versions?
Choosing a version inside each range means asking Hex which releases exist. With a manifest.toml present, the build asked Hex nothing and took its packages from the download cache.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
What does the range >= 1.0.0 and < 2.0.0 let a build pick?
Any release from 1.0.0 up to, but not including, 2.0.0. Under semantic versioning those bring fixes and new functions, but no breaking change, which only a new major may bring.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
What does the Gleam compiler write for each of its two targets?
For Erlang, the default, .erl source compiled to .beam bytecode for the BEAM; for JavaScript, ES modules (.mjs) for a runtime such as Node.js. Both are meant to be read when debugging.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
What does gleam format --check do in a CI run?
It changes nothing and fails when a file is not in the formatter's one layout, naming the file. gleam format src rewrites such files; the formatter has no style settings.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
How do you port list.range(1, 10) to gleam_stdlib 1.0?
list.range is gone, and int.range stops before its to value: int.range(from: 1, to: 11, with: 0, run: int.add) sums 1 to 10. Writing to: 10 would silently drop the 10.
From the lesson Gleam on Erlang/OTP 29 and Node.js: first project
-
A fourth variant, Triangle, is added to a Gleam type. What happens to the case expressions over it?
Every one that does not handle Triangle stops the build with Inexhaustive patterns, listing the missing pattern. A catch-all _ branch would hide it instead, so name every variant.
From the lesson Gleam for JavaScript and Python developers
-
How does a Gleam function say that it can fail?
It returns the built-in Result: Ok(value) or Error(reason), as in Result(Int, String), and every caller must handle both. Gleam uses no exceptions for expected failures.
From the lesson Gleam for JavaScript and Python developers
-
What does use age <- result.try(parse_age(text)) do with the lines below it?
They become a function that result.try calls with the value inside Ok. An Error is returned at once, so a chain of failing steps stays flat.
From the lesson Gleam for JavaScript and Python developers
-
When is let assert the right tool in Gleam?
For a value the code has already checked and cannot work without: it crashes with your message if the pattern does not match. User input should get an Error instead.
From the lesson Gleam for JavaScript and Python developers
-
What does |> do, and what do labelled arguments add to a Gleam call?
|> passes the value on its left as the first argument of the call on its right, so data reads left to right. Labels such as discount: and delivery: let a call give its arguments in any order.
From the lesson Gleam for JavaScript and Python developers
-
What are -7 / 2, -7 % 2 and 7 / 0 in Gleam?
−3, −1 and 0: / truncates, and division by zero is defined as zero. int.floor_divide(-7, 2) gives Ok(-4) and int.modulo(-7, 2) gives Ok(1), Python's results, as Results.
From the lesson Gleam for JavaScript and Python developers
-
Where do Gleam's two targets give different whole numbers?
Beyond 2^53: on the BEAM an Int has no size limit, so 2^53 + 1 is 9007199254740993, while on JavaScript an Int is a 64-bit float and gives 9007199254740992.
From the lesson Gleam for JavaScript and Python developers
-
Why does one call into gleam_erlang stop the JavaScript build of a whole project?
gleam_erlang's functions are externals implemented in Erlang only, so each use is an Unsupported target error, and a build compiles every module in src. Shared modules import only what builds for both.
From the lesson Gleam for JavaScript and Python developers
-
What is a process on the BEAM?
A lightweight unit of execution with its own memory and its own mailbox. Processes share no data and cooperate by sending messages; in Gleam, process.spawn starts one.
From the lesson Gleam processes, actors and FFI
-
Who may send to a Gleam subject, and who may receive from it?
Any process may send to it, but only the process that created it may receive; receive panics anywhere else. Create the subject in the process that waits for the answers.
From the lesson Gleam processes, actors and FFI
-
What does process.receive(results, within: 100) give when no message arrives?
Error(Nil), after 100 ms. A receive with a timeout is a Result, so a process never waits forever by accident.
From the lesson Gleam processes, actors and FFI
-
Why did the program sort the five squares before printing them?
Messages reach the mailbox in whatever order the processes happened to run, so output that depended on that order would change from run to run.
From the lesson Gleam processes, actors and FFI
-
Why could two buyers never both take the last unit from the stock actor?
The actor takes its messages one by one, each against the state the previous one left, so a check and an update in one handler call are never split. 4 of 10 buyers got the 4 units, with no lock.
From the lesson Gleam processes, actors and FFI
-
A supervised stock actor crashes after reserving 2 of 5 units. What does Left answer after the restart?
5. A supervisor restarts a child from its starting state, so the reservation died with the old process. State that must survive goes to a database or a log first.
From the lesson Gleam processes, actors and FFI
-
When does a gleam_otp static supervisor stop restarting a crashing child?
After more than 2 restarts within 5 seconds, its default restart intensity. It then ends with reached_max_restart_intensity, shuts down its children and takes linked callers down too.
From the lesson Gleam processes, actors and FFI
-
What does the Gleam compiler check about the type of an @external function?
Nothing: it cannot read the foreign code, so it trusts the declared type. Binding erlang:length/1 to a String compiled and then stopped at run time with badarg.
From the lesson Gleam processes, actors and FFI
-
What runs when a hold on a seat expires in the booking core?
No timer fires and no cleanup job runs. Expiry is a rule about reading: the next time anyone looks at the show, a hold past its until counts as an open seat.
From the lesson Project: a ticket-booking core in Gleam
-
What does all or nothing mean for a hold?
A hold gets every seat it asks for or none: hold checks all the seats before it writes any, so after SeatTaken("A2"), A1 is still free.
From the lesson Project: a ticket-booking core in Gleam
-
Why is Show declared as an opaque type?
Other modules can hold a Show and hand it back but can neither build one nor look inside, so nobody marks a seat Sold except through confirm and its rules.
From the lesson Project: a ticket-booking core in Gleam
-
Why does every booking function take now as an argument?
So that none of them reads a clock: the same show, request and time always give the same answer, and a test can check the exact instant of expiry without waiting 600,000 ms.
From the lesson Project: a ticket-booking core in Gleam
-
A hold made at 10:06 is confirmed at 10:16, exactly hold_ms later. What does the core say?
That it has expired: a hold has expired once until <= now, so at that very instant another buyer may hold its seat.
From the lesson Project: a ticket-booking core in Gleam
-
Why do the eight booking tests pass on the BEAM and on Node.js alike?
The core imports only gleam_stdlib and depends on no process, clock or mailbox order. The actor that serves it sits in a separate package that runs on Erlang only.
From the lesson Project: a ticket-booking core in Gleam
-
Fifty buyers ask for A1 at once. Why does exactly one win, and why does the test not name the winner?
One actor per show handles one Hold at a time, checking and changing together. The 50 requests reach its mailbox in no fixed order, so the winner can change between runs.
From the lesson Project: a ticket-booking core in Gleam
-
Why did naive_server sell seat A1 to two buyers?
Asking IsFree and sending Take were separate messages, so both buyers heard True before either took the seat: a race condition. A single Hold that checks and changes together closes it.
From the lesson Project: a ticket-booking core in Gleam
-
What does nim c -r --hints:off hello.nim do, step by step?
c picks the C backend: Nim writes C files, clang compiles and links them, and -r runs the program once the build succeeds. --hints:off hides the compiler's progress lines.
From the lesson Nim 2.2: install, build modes and backends
-
Where does a Nim build keep the C code it writes?
In the nimcache, such as ~/.cache/nim/hello_d for a debug build: a C file per module with its object file beside it, and hello.json, Nim's record of the build.
From the lesson Nim 2.2: install, build modes and backends
-
An int8 holding 127 gets 1 added. What do the debug, release and danger builds do?
Debug and release stop with an OverflowDefect and exit status 1, only debug naming the line. Danger prints -128 and ends with exit status 0, as if nothing were wrong.
From the lesson Nim 2.2: install, build modes and backends
-
What does -d:release change compared with a debug build?
It switches the optimiser on, -O3 for clang, and stack traces and line tracing off, but it keeps every run-time check, so an overflow still stops the program.
From the lesson Nim 2.2: install, build modes and backends
-
Why ship -d:release and not -d:danger?
A danger build drops the run-time checks, overflow, range and bounds among them, and the assertions too, so a mistake becomes a wrong value with exit status 0 instead of a stop.
From the lesson Nim 2.2: install, build modes and backends
-
What does nimpretty settle in a Nim file, and what did it leave alone?
Layout: single spaces after commas and around =, and indentation, with --indent:2 giving NEP 1's two spaces. Choices such as w*h it left as written.
From the lesson Nim 2.2: install, build modes and backends
-
How big is an int on Nim's JavaScript backend?
32 bits: int takes the size of a pointer on its platform, so high(int) is 2,147,483,647 and sizeof(int) is 4 there, against 64 bits on the C backend.
From the lesson Nim 2.2: install, build modes and backends
-
Three payments of a billion paise each are added up in an int. Why did only the JavaScript build stop?
The total, 3,000,000,000, does not fit the 32-bit int of that backend, so it raised an OverflowDefect. Declared int64, the total printed on Node.js as well.
From the lesson Nim 2.2: install, build modes and backends
-
What does Python's collections.Counter become in Nim?
A CountTable from std/tables: toCountTable(sold) counts the items of a seq, and counts.largest.key gives the one counted most.
From the lesson Nim for Python developers: types and procs
-
How do const, let and var differ in Nim?
const is fixed while compiling, let once while the program runs, var never. The compiler refuses a second assignment to a let and a const that needs a run-time value such as stdin.
From the lesson Nim for Python developers: types and procs
-
Are item.describe(9) and describe(item, 9) different calls in Nim?
No. Method-call syntax lets obj.f(args) stand for f(obj, args) whatever the type of the first argument, so a proc defined in any module reads like a method.
From the lesson Nim for Python developers: types and procs
-
With type Item = object, what happens to a after var b = a; b.stock = 0?
Nothing: an object is copied field by field when assigned. A ref object would be shared by both names, the way Python's class instances are.
From the lesson Nim for Python developers: types and procs
-
Why does the compiler refuse item.stock -= 1 inside for item in items?
A plain for over a seq hands out each item read-only, so the field is immutable, not var. for item in items.mitems hands each item out so it can be changed in place.
From the lesson Nim for Python developers: types and procs
-
What are -7 div 2 and -7 mod 2 in Nim, and how do you get Python's answers?
−3 and −1, because div truncates and the remainder keeps the dividend's sign. floorDiv and floorMod from std/math give Python's −4 and 1.
From the lesson Nim for Python developers: types and procs
-
Why is len("naïve") 6 in Nim but 5 in Python?
A Nim string holds UTF-8 bytes, and ï takes two of them; Python counts characters. runeLen from std/unicode counts the 5 runes.
From the lesson Nim for Python developers: types and procs
-
Why does except CatchableError not catch an IndexDefect?
Defects are bugs, such as an index past the end, and inherit from Defect, not CatchableError. Even except IndexDefect stops working with --panics:on, so check the index instead.
From the lesson Nim for Python developers: types and procs
-
Why did the template square(nextId()) return 2 where a proc returned 9?
A template pastes its argument as written, so x * x turned into nextId() * nextId() and ran nextId twice. A proc evaluates every argument exactly once.
From the lesson Nim macros, ARC/ORC memory and backends
-
How do you make a Nim template evaluate its argument only once?
Bind the argument to a local inside the template, as (let v = x; v * v) does, or use a proc instead of a template.
From the lesson Nim macros, ARC/ORC memory and backends
-
What does a Nim macro receive, and what becomes of what it returns?
It receives the syntax trees of its arguments, unchecked when they are untyped. The tree it returns replaces the call and is checked like code written by hand.
From the lesson Nim macros, ARC/ORC memory and backends
-
When do dumpTree and expandMacros print?
While nim c compiles the file: their lines appear in the build's output, never in what the program prints.
From the lesson Nim macros, ARC/ORC memory and backends
-
Why does const f30 = fib(30) cost the running program nothing?
Assigning to a const makes the compiler call fib(30), so 832,040 is part of the program before it runs. staticRead brings a file's text in the same way.
From the lesson Nim macros, ARC/ORC memory and backends
-
Why can a const not use abs imported from C with importc?
Compile-time code runs only Nim the compiler can see. A C function exists only after the C compiler has run, which happens after the compile-time code.
From the lesson Nim macros, ARC/ORC memory and backends
-
In the Ticket example, why did var b = a copy, while keep(b) moved?
a was used again later, so the compiler inserted =copy. keep(b) was the last use of b, so the value was moved into it and no copy hook ran.
From the lesson Nim macros, ARC/ORC memory and backends
-
Two refs point at each other. What do ARC and ORC do once the proc that made them returns?
Neither frees them at once, as each count stays at 1. ORC's cycle collector, run by GC_fullCollect(), freed both; under --mm:arc they leaked.
From the lesson Nim macros, ARC/ORC memory and backends
-
When is a log line valid for loglens?
Four fields with single spaces and nothing after them: a method of capitals A to Z, a path starting with /, a status of three digits from 100 to 599, and 1 to 9 digits followed straight away by ms.
From the lesson Project: a log analyser in Nim
-
In what order does loglens list its endpoints, and how does one sort give it?
Most requests first, equal counts by name byte by byte. Sorting (minus count, name) pairs gives both orders, because tuples compare field by field.
From the lesson Project: a log analyser in Nim
-
Why does loglens read its input with for line in file.lines?
It streams the file one line at a time instead of holding it in memory, and it drops each line ending, so a log with Windows line endings reads the same.
From the lesson Project: a log analyser in Nim
-
Why does record fetch its endpoint with mgetOrPut?
mgetOrPut returns the table's own entry as var, so the counts change inside the table rather than in a copied object.
From the lesson Project: a log analyser in Nim
-
What did the first draft, with scanf's $i, accept that the specification forbids?
+200, 0200 and 2_00 as 200, and a latency of -5, and twenty digits raised a ValueError. The final rule uses digits(3, 3) and digits(1, 9), which check each character.
From the lesson Project: a log analyser in Nim
-
How is the nearest-rank p95 found, and why is it always a latency that happened?
Sort the latencies and take the one at rank ⌈0.95 × n⌉, which is (95 * n + 99) div 100 in whole numbers. It picks a recorded value, never one in between.
From the lesson Project: a log analyser in Nim
-
Why did every p95 in the report of sample.log equal its maximum?
For 19 values or fewer the nearest rank lands on the last one. In the million-line log, with 50,044 requests or more per endpoint, p95 fell well below the maximum: 94 ms against 491 ms for GET /api/orders.
From the lesson Project: a log analyser in Nim
-
What do loglens's five black-box cases compare, and on which programs?
A log in and a report out, byte for byte against an expected file, on the native build and on the Node.js build of the same core. All ten runs passed.
From the lesson Project: a log analyser in Nim
-
Which three pins does the Elm mini-course check, and why does elm-test have its own?
elm 0.19.3, Node.js v24.21.0, which runs the compiled programs and elm repl, and elm-test 0.19.3-0. The test runner is not part of the compiler: it comes from npm.
From the lesson Elm 0.19.3: install, build and run headlessly
-
What does an Elm application's elm.json record about its packages?
Every direct and indirect dependency, each at one exact version such as elm/core 1.0.5, so the file doubles as a lock file. A package's own elm.json lists ranges instead.
From the lesson Elm 0.19.3: install, build and run headlessly
-
Why did elm init fail on a computer with an empty ~/.elm and no network?
It needs the list of all published packages from package.elm-lang.org. Once ~/.elm holds that list and the packages, elm init and builds work offline.
From the lesson Elm 0.19.3: install, build and run headlessly
-
Which of elm.json and elm-stuff belong in version control?
elm.json, which fixes every version of the build. elm-stuff is a cache of compiled modules that elm make rebuilds whenever it is missing.
From the lesson Elm 0.19.3: install, build and run headlessly
-
What does elm make --optimize do, and how much did it save on the Orders worker?
It shortens record field names and unboxes values. On a 65,875-byte worker that saved 567 bytes, 0.9 %, since most of the file is runtime and core code; a minifier does the real shrinking.
From the lesson Elm 0.19.3: install, build and run headlessly
-
What does dead code elimination remove in every Elm build?
Every function that main cannot reach, across all packages, which is possible because every package on the package site is written entirely in Elm.
From the lesson Elm 0.19.3: install, build and run headlessly
-
What is a Platform.worker program?
An Elm program with no user interface, built from init, update and subscriptions. It shows results only through ports, so Node.js can run it with no browser.
From the lesson Elm 0.19.3: install, build and run headlessly
-
Why did late.cjs, which subscribed to the port from a timer, receive 0 messages?
The receipt comes from init, and the runtime delivers it once the code that called init() finishes its turn. Subscribe to each port right after init() returns.
From the lesson Elm 0.19.3: install, build and run headlessly
-
What does { chai | quantity = 3 } do in Elm?
It builds a new record with quantity 3 and the other fields copied, like { ...chai, quantity: 3 }. chai stays as it was, since Elm has no assignment.
From the lesson Elm for JavaScript developers
-
withTax : Int -> Int -> Int. What is withTax 5?
A function that adds five percent to a price: every Elm function is curried, so fewer arguments give a function back, ready for List.map (withTax 5).
From the lesson Elm for JavaScript developers
-
Why model a loading screen as one custom type rather than loading, error and data fields?
Three fields allow 8 combinations, 5 of which no screen can draw. Loading, Loaded (List Order) and Failed String allow exactly the three real states.
From the lesson Elm for JavaScript developers
-
A variant is added to a type and a case over it is not updated. What does the compiler do?
It stops with MISSING PATTERNS, quoting the case and listing the missing variant, so every case that must learn about it is found before the program runs.
From the lesson Elm for JavaScript developers
-
What does String.toInt "4e1" return in Elm?
Nothing: it accepts digits with an optional sign and nothing else, while JavaScript's Number("4e1") gives 40.
From the lesson Elm for JavaScript developers
-
What do modBy 2 -7 and remainderBy 2 -7 return, and what does modBy 0 do?
1 and −1: modBy takes the sign of the modulus, remainderBy that of the number divided, like JavaScript's %. modBy 0 stops the program, while 7 // 0 is simply 0.
From the lesson Elm for JavaScript developers
-
Why is truncate 3.0e9 −1294967296 in Elm?
elm/core computes truncate as n | 0 and // as (a / b) | 0, and JavaScript's | works on 32 bits, so results past 2,147,483,647 wrap. floor 3.0e9 gives 3000000000.
From the lesson Elm for JavaScript developers
-
How can a deploy ship an old build after elm make --optimize refuses a Debug.log?
The screen may still end with Success! while the exit status is 1, and the old file stays. Stop the script on the status, with set -e or &&, and build into a fresh folder.
From the lesson Elm for JavaScript developers
-
What are the four pieces of The Elm Architecture?
The model, holding the whole state; a Msg type listing everything that can happen; update, giving the next model for a message; and view, describing the page for a model.
From the lesson The Elm Architecture, JSON and ports
-
Who calls update and view in an Elm program?
The runtime. It calls init once, view for each new model and update for each message, and it keeps the model: your code only returns values, so update can be tested on its own.
From the lesson The Elm Architecture, JSON and ports
-
How do Browser.sandbox and Browser.element differ?
Both own one node of a page. sandbox has no commands, subscriptions, flags or ports; element adds Cmd, Sub, flags and ports.
From the lesson The Elm Architecture, JSON and ports
-
In what order do the results of a Cmd.batch arrive?
In no promised order: all the commands go to the runtime at once, and Batch's first, second and third came back as third, second, first. Send one message that holds everything in order.
From the lesson The Elm Architecture, JSON and ports
-
What did the Elm decoder report for an order whose second price was sent as "1450"?
A failure at json.items[1].paise, Expecting an INT, naming the bad field. JavaScript instead turned the sum 1200 + "1450" into the text 12001450.
From the lesson The Elm Architecture, JSON and ports
-
Why is Decode.maybe risky for an optional field?
It reads a value of the wrong type as Nothing, as quietly as a missing one, so "note": 42 passed with no note. A decoder that allows only a missing field or null refuses it.
From the lesson The Elm Architecture, JSON and ports
-
What happens when JavaScript sends the text '1450' into an Elm port typed Int?
send throws in the JavaScript that called it. A port of type Json.Decode.Value lets Elm decode the value and turn a bad one into a message, as TillSafe did.
From the lesson The Elm Architecture, JSON and ports
-
Why must a port subscriber show user text with textContent and never innerHTML?
innerHTML parses the text as markup, so Asha <b>VIP</b> becomes a bold element, the start of cross-site scripting. textContent makes a text node, as Elm's own Html.text does.
From the lesson The Elm Architecture, JSON and ports
-
How does the splitter round tax and tip without any floats?
Each is a percentage of an item's price in whole paise, rounded half up on its own with (paise * percent + 50) // 100, so 72.5 paise of tax becomes 73.
From the lesson Project: a bill-splitter app in Elm
-
How do one item's parts always add up to its line total?
splitAmong gives each sorted sharer amount // count, then one more paisa to the first leftover names, where leftover = amount - base * count lies from 0 to count - 1.
From the lesson Project: a bill-splitter app in Elm
-
Why did Asha pay both odd paise of the dinner, and what is the catch?
Leftover paise go to sharers in alphabetical order, and Asha comes first. The rule is easy to check, but over many bills it always favours the same names.
From the lesson Project: a bill-splitter app in Elm
-
Why does the splitter cap prices at 100000.00 rupees?
To keep every quotient in the core far below 2,147,483,647, past which Elm's // wraps.
From the lesson Project: a bill-splitter app in Elm
-
What does the splitter's fuzz test check, and why does it run with --seed 42?
That the shares add up to the bill for generated lists of prices and sharers. The fixed seed makes elm-test generate the same inputs in every run.
From the lesson Project: a bill-splitter app in Elm
-
What is shrinking in elm-test?
After a fuzz failure, elm-test tries smaller inputs that still fail. The broken splitter came down to one item of 1 paisa shared by two: Given ([1],2).
From the lesson Project: a bill-splitter app in Elm
-
Why does the form keep what was typed as text in its model?
A half-typed price such as 145. is not a mistake yet, and parsing early would lose what was typed. toBill parses when the view needs numbers and lists every problem at once.
From the lesson Project: a bill-splitter app in Elm
-
Why are uglifyjs's pure_funcs and unsafe flags safe for compiled Elm, and what did they save?
Compiled Elm has no side effects outside the runtime, so dropping unused calls cannot change it. The app went from 135,770 bytes to 23,942 minified, 9,282 gzipped.
From the lesson Project: a bill-splitter app in Elm
-
Why did every build stop with can't find file 'prelude' once embedded/bin went first on the PATH?
crystal then named the bare compiler binary instead of bin/crystal, the script that sets CRYSTAL_PATH. Put bin first and embedded/bin after it, or link shards elsewhere.
From the lesson Crystal 1.21: install, compile, test, shards
-
What does the tarball's bin/crystal script set before it starts the compiler?
CRYSTAL_PATH, where the compiler looks for the files a program requires, and CRYSTAL_LIBRARY_PATH, where it looks first for C libraries, both inside the unpacked release.
From the lesson Crystal 1.21: install, compile, test, shards
-
Does crystal run interpret a .cr file?
No. It compiles the whole program into an executable in a temporary place and runs that; crystal build keeps the executable. Either way every type is checked first.
From the lesson Crystal 1.21: install, compile, test, shards
-
What does typeof(short) print when short comes from shelf.find { … }?
(Book | Nil), because find may find nothing; the compiler works out that type for the whole program before any of it runs.
From the lesson Crystal 1.21: install, compile, test, shards
-
What does --release add to a Crystal build, and when is it worth the wait?
It means -O3 --single-module, optimising the whole program as one unit. It builds slowly, so it is for programs you ship and benchmarks; hello.cr fell from 1,830,920 to 549,440 bytes.
From the lesson Crystal 1.21: install, compile, test, shards
-
What does the first crystal spec of a new project report?
1 examples, 1 failures, with exit status 1: the generated spec checks false.should eq(true) on purpose. The output names the command that reruns it, crystal spec spec/tally_spec.cr:6.
From the lesson Crystal 1.21: install, compile, test, shards
-
Why do tally's specs require src/tally.cr and never src/cli.cr?
crystal spec compiles the spec files and all they require into one program, so requiring the command-line file would run the tool. shard.yml's target points at src/cli.cr instead.
From the lesson Crystal 1.21: install, compile, test, shards
-
Which shards files does an application keep in version control, and which does a library?
An application commits both shard.yml and shard.lock, so each machine gets identical versions. A library commits only shard.yml, leaving its users to lock their own; crystal init lib ignores shard.lock.
From the lesson Crystal 1.21: install, compile, test, shards
-
What is the difference between typeof(x) and x.class in Crystal?
typeof gives the type the compiler worked out over every branch, such as (Int32 | String); .class gives the class of the value at that moment of the run, such as String.
From the lesson Crystal for Ruby developers: types and nil
-
When may a method be called on a value of a union type?
Only if every type in the union has it. label + 1 does not compile for (Int32 | String), because a String has no + that takes an Int32.
From the lesson Crystal for Ruby developers: types and nil
-
Why does Crystal refuse prices["juice"]? * 2 before the program runs?
[]? returns the price or nil, so its type is (Int32 | Nil), and Nil has no *. Ruby met the same mistake only when the run reached the missing key.
From the lesson Crystal for Ruby developers: types and nil
-
How do you use a lookup that may be nil without reaching for not_nil!?
Test it: inside if price = prices[item]? the compiler knows price is an Int32. A default such as || 0 or fetch fits only where a number is really right for a missing key.
From the lesson Crystal for Ruby developers: types and nil
-
What do [1, 2].each { … } and 'a'.class give in Crystal, unlike Ruby?
each returns nil, not the array, and single quotes make a Char, one character. A String needs double quotes.
From the lesson Crystal for Ruby developers: types and nil
-
What happens at Int32::MAX + 1 in Crystal, and what are the ways on?
It raises OverflowError. Widen with to_i64, wrap on purpose with &+, which gave -2147483648, or use BigInt, which needs the GMP library at build and run time.
From the lesson Crystal for Ruby developers: types and nil
-
What is 7 / 2 in Crystal, and which operator matches Ruby's integer /?
3.5, a Float64: / converts to Float64 first, which is also why 7 / 0 gives Infinity. // is floor division, so -7 // 2 is -4, as Ruby's -7 / 2 is.
From the lesson Crystal for Ruby developers: types and nil
-
What do 2.5.round and -2.5.round give in Crystal and in Ruby?
Crystal: 2.0 and -2.0, halves to the even neighbour, as Float64. Ruby: 3 and -3, away from zero, as Integer. Crystal's round(:ties_away) gives 3.0.
From the lesson Crystal for Ruby developers: types and nil
-
When does a Crystal macro run, and what are its arguments?
Inside the compiler, while the program compiles. Its arguments are pieces of the program, such as the name metre, not values; {% %} runs loops and conditions and {{ }} pastes values in.
From the lesson Crystal macros, fibers and C bindings
-
How do you see the code a macro call wrote?
crystal tool expand -c file.cr:line:column file.cr, giving the line and column of the call. It prints the generated methods as if they had been typed.
From the lesson Crystal macros, fibers and C bindings
-
How do Crystal fibers share one thread?
Cooperatively: one runs at a time and keeps the thread until it waits on a channel, input, output or a sleep, or until it ends.
From the lesson Crystal macros, fibers and C bindings
-
Why did fibers 1 and 2 of round_trip.cr never print their last line?
A send on a channel with no room waits for a receiver. They waited, main took their values and finished, and a program ends with its main fiber, whatever the others still have to do.
From the lesson Crystal macros, fibers and C bindings
-
What changed when round_trip.cr's channel was given room for three values?
No send had to wait, so each fiber printed both lines before the next started. The values were still [0, 1, 4]; the order of everything else changed.
From the lesson Crystal macros, fibers and C bindings
-
Why does each result of the worker pool carry its host's index?
Results arrive in the scheduler's order, not the input's, so main sorts by index and the report reads in input order whoever did the work.
From the lesson Crystal macros, fibers and C bindings
-
What does C's strlen return for the Crystal strings चाय and "tea\0coffee"?
9 and 3: C counts bytes and stops at the first zero byte. check_no_null_byte raises an ArgumentError for such a string before it reaches C.
From the lesson Crystal macros, fibers and C bindings
-
Why was a proc that reads the local variable descending refused as a qsort callback?
It is a closure, and a C function pointer has no room for the variables it carries. Pass a proc without a closure, and send data through a user-data pointer when C offers one.
From the lesson Crystal macros, fibers and C bindings
-
Which line does csv2json name for an error in a record?
The line where the record starts, the one an editor shows. A quoted cell with a line break makes a record span lines: B-103 is the fourth record but starts on line 5.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
How does csv2json work out where each record starts?
It begins at 1 and, after each record, adds one for its own line break and one per line break inside its cells; Crystal's CSV reader returns records without lines.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
Why did Python's csv.reader give line 4 for B-102 where csv2json gives 3?
line_num counts the lines read so far, which after a two-line record is where it ends. Neither is wrong, so the specification states which line is reported.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
What does csv2json do with a file that has four bad cells?
It reports all four in file order, as line N, column NAME: … on standard error, writes no JSON at all and ends with exit status 1.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
Why does csv2json drop a byte-order mark before it checks the header?
Some programs begin UTF-8 files with U+FEFF. Left in, the first column would be named \u{FEFF}code, and a header that looks right in every editor would fail.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
Which int cells does Crystal's to_i64? accept that csv2json's rule refuses?
" 212" with its space, and "+212". csv2json first tests an int cell against /\A-?[0-9]+\z/ and only then converts it.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
Why does csv2json never put a price through a float?
4.35 as a float times 100 is 434.99999999999994, which cuts to 434, a paisa short. It reads rupees and up to two decimals as two integers, so 349.5 is exactly 34,950.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
Why is the JSON, and not the CSV, the canonical form of csv2json's data?
json2csv writes 499.5 back as 499.50 and 149 as 149.00, because the JSON holds paise. Converted back, the JSON is identical; the CSV text is not.
From the lesson Project: a CSV-to-JSON converter in Crystal
-
Split −1,051 paise between two diners with each language's first integer division. What do the four languages give?
Crystal's // and Tcl's / floor, giving −526; Objective-C's / and Visual Basic's \ truncate, giving −525. A paisa per diner, decided by a default.
From the lesson Capstone: one spec in twelve languages
-
How does the capstone round a ÷ b half up using integers only?
(2a + b) div (2b) with floor division, below zero too. The coupon's tax of −50.05 paise becomes −50 in every language that floors.
From the lesson Capstone: one spec in twelve languages
-
How does the capstone hold a tax rate of 2.5 %, and why?
As 250 basis points; a basis point is a hundredth of one percent. The tax is then the price times 250, divided by 10,000, all in whole numbers.
From the lesson Capstone: one spec in twelve languages
-
Where do a line's leftover paise go?
One each to the line's first diners in byte order of their names, so that the shares add up exactly to the line total.
From the lesson Capstone: one spec in twelve languages
-
In which order are the diners reported, and why does Visual Basic's Array.Sort get it wrong?
Byte order: Bilal, Zoya, asha. Array.Sort follows the computer's language setting and gave asha Bilal Zoya; StringComparer.Ordinal sorts by bytes everywhere.
From the lesson Capstone: one spec in twelve languages
-
What is a test vector here, and what does check.sh compare?
A bill with the exact output it must give. check.sh runs a program on every vector and compares standard output, standard error and exit status byte for byte, so it grades any language.
From the lesson Capstone: one spec in twelve languages
-
Why did naive.cr, which rounded with Crystal's round, fail vectors 06 and 08 only?
Those are the two whose taxes land exactly on a half, and Crystal's round goes to the even neighbour: 0.5 paise became 0 and 2.5 became 2. The other eighteen passed.
From the lesson Capstone: one spec in twelve languages
-
Why does typeof(2 * 1_000_000_000_i64) print Int32 in Crystal?
The result takes the type of the left operand, Int32 here, so 2 * a may overflow while a * 2 is an Int64. half_up therefore puts the Int64 first.
From the lesson Capstone: one spec in twelve languages
Back to the Language Atlas (mini-courses for more languages) track