Nim, lesson 3
Your exercises receive their input on standard input (stdin), one line at a time, as if
someone typed it. Nim's standard input is the stdin file.
readLine(stdin) reads one line and gives it back as a string, without the line break. You will
often see it written in method style, stdin.readLine(); Nim lets you call any procedure as
first.proc(rest), and both forms mean the same thing.
If there is no line left to read, readLine raises an EOFError and the program stops. The
exercises always give you the lines they promise, so for now that is fine.
Input is always text, and Nim will not mix text and numbers for you: "7" + 1 does not compile.
The module has the converters you need:
2 exercises to try what you just read.
strutilsstrip removes spaces and line-ending characters from both ends, which protects you from
stray whitespace in the input.parseInt turns "42" into the int 42.parseFloat turns "36.6" (or "37") into a float.Both raise a ValueError if the text is not a valid number.
| Expression | Result | Meaning |
|---|---|---|
7 + 2 | 9 | add |
7 - 2 | 5 | subtract |
7 * 2 | 14 | multiply |
7 / 2 | 3.5 | divide, always a float |
7 div 2 | 3 | whole-number division |
7 mod 2 | 1 | remainder |
div and mod are words, not symbols. Multiplication and division happen before addition and
subtraction, and parentheses change the order.
A number literal written in your code adapts to its neighbour, so celsius * 9 works fine when
celsius is a float. Two variables of different types are another story: Nim never silently
turns an int variable into a float. You convert it yourself:
This strictness can feel fussy at first, but it means a number never changes type by accident.
A group shares some pizza slices equally. Every person gets the same whole number of slices, and the rest are left over.
Input: two lines. The first is the number of slices (0 or more), the second the number of people (1 or more).
Output: two lines:
That sample is for the input:
Read a temperature in degrees Celsius and print it in Fahrenheit, using
F = C * 9 / 5 + 32.
Input: one line with a number, which may have a decimal part (36.6) or not (100).
Output: just the Fahrenheit value. Any normal float form is accepted, so 212.0 and 212
both count for 100 °C.
prints
let name = stdin.readLine()
echo "Hi, ", name, "!"import std/strutils
let age = stdin.readLine().strip().parseInt()
let height = parseFloat("1.75")let people = 4
let bill = 50.0
echo bill / toFloat(people) # 12.5
echo bill / float(people) # the same: a type name converts too
echo int(12.9) # 12, the fractional part is droppedEach person gets 3 slices.
Leftover: 214
43798.6