Chuyển đến nội dung

Bài 17 · Collections and Strings

Tuples and Option: Grouping and Maybe-Values

Group values with Nim tuples, return several results from a procedure, unpack them, and model a missing value safely with std/options instead of nil or magic numbers.

Sometimes you want to keep two or three values together without defining a whole type, for example a pair of coordinates or a function's two results. Nim's tuples do exactly that. A related problem is the answer that might not exist: the first even number in a list, the user with a given ID. The standard library answers with Option[T], a value that is either "something" or "nothing".

Nim code in this lesson is read-only (no compiler on this site). The C stand-ins are runnable and show the same ideas.

Tuples

NIM
let point = (3, 4)                        # an unnamed tuple of (int, int)
echo point[0], " ", point[1]              # 3 4

let person = (name: "Ada", age: 36)       # named fields
echo person.name                          # Ada
echo person.age + 1                       # 37

A tuple has a fixed number of fields, each with its own type, and is a value type (copied on assignment). Write the type of a named tuple as tuple[name: string, age: int], or give it a name:

NIM
type
  Point = tuple[x, y: int]

let origin: Point = (x: 0, y: 0)

Tuples are compared structurally: two tuples are equal when all fields are equal, and the comparison operators order them field by field. They are also hashable, so tuples are excellent table keys:

NIM
import std/tables

var visited = initTable[(int, int), bool]()
visited[(2, 3)] = true
echo (2, 3) in visited          # true

Unpacking

NIM
let (x, y) = point
let (name, age) = person        # names the fields in order
echo name, " ", age

var (a, b) = (1, 2)
(a, b) = (b, a)                 # swap without a temporary
echo a, " ", b                  # 2 1

Use _ to ignore a field: let (_, y) = point.

Returning several values

Nim procedures return one value, but that value can be a tuple, so you get multiple results cheaply:

NIM
func minMax(values: openArray[int]): (int, int) =
  result = (values[0], values[0])
  for v in values:
    if v < result[0]: result[0] = v
    if v > result[1]: result[1] = v

let (lo, hi) = minMax([4, 9, 2, 7])
echo lo, " ", hi                # 2 9

For results that deserve names, return a named tuple: : tuple[lo, hi: int]. Then callers can write r.lo and r.hi.

Tuples versus objects

Tuple Object (later lesson)
Declared with (a, b) or tuple[...] type T = object
Equality structural, between any matching tuples only same type
Methods, inheritance no yes
Best for small, short-lived groups domain concepts

Option: a value that may be absent

Languages often use nil, -1 or an exception to say "not found". Each has problems: nil is easy to forget to check, -1 can be mistaken for a real value, and exceptions are heavy for something that is a normal outcome. Option[T] makes the possibility part of the type:

NIM
import std/options

func firstEven(values: openArray[int]): Option[int] =
  for v in values:
    if v mod 2 == 0:
      return some(v)
  none(int)

let r = firstEven([1, 3, 6, 8])
if r.isSome:
  echo "found ", r.get          # found 6
else:
  echo "no even number"

some(x) wraps a value, none(T) is the empty case. The caller cannot use the result as an int without opening the box, which forces them to think about the empty case.

Useful operations:

Call Meaning
isSome, isNone test
get the value; raises UnpackDefect if empty
get(default) or opt.get(0) the value, or a fallback
map(proc) transform the value if present
filter(proc) keep it only if the predicate holds
NIM
import std/[options, sugar]

let doubled = firstEven([2, 4]).map(x => x * 2)
echo doubled.get(-1)            # 4
echo firstEven([1, 3]).get(-1)  # -1
flowchart TD
  A["firstEven(values)"] --> B{"found an even?"}
  B -- yes --> S["some(value)"]
  B -- no --> N["none(int)"]
  S --> U["caller: isSome / get / map"]
  N --> U

Caption: the empty case is a first-class value, not a special number or a crash.

When to use what

  • Missing value is normal (lookup, search, optional config): Option[T].
  • Failure is exceptional (disk gone, bad format): raise an exception.
  • A table lookup you expect to succeed: table[key]; if absent is normal, use getOrDefault or hasKey.

Stand-in: tuple-like results in C

C has no tuples, but a small struct plays the same role. This stand-in returns minimum and maximum together.

C Stand-in: returning two values with a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: an Option as a tagged struct

An Option[int] is essentially a flag plus a value. This stand-in builds one, showing why the type forces you to check.

C Stand-in: Option[int] as a tagged struct

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The result -1 appears only because we asked for a fallback with getOr, in the same way get(-1) works in Nim.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How do you get several results out of a Nim procedure?

    A procedure returns one value, which can be a tuple holding several results.
  2. 2. What does let (x, y) = point do?

    Tuple unpacking declares variables from the fields in order.
  3. 3. Why prefer Option[T] over returning -1 for 'not found'?

    Option prevents mistaking a sentinel for a real value and makes the empty case explicit.
  4. 4. What does opt.get(0) return when opt is none?

    get with a default returns the fallback for an empty Option.

Summary

  • Tuples group a fixed number of values, optionally with field names; they are value types compared field by field.
  • Unpack with let (a, b) = t; return tuples to give a procedure several results.
  • Option[T] from std/options models a missing value: some, none, isSome, get, map.
  • Use Options for normal absence and exceptions for real failures.

Next: Strings and runes

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.