Skip to content
العربية

17. Tuples and multiple return values

To write a function that returns more than one value in a single call, and to unpack its result into names.

  • A tuple is a struct without a name: ordered values, each with a name and a type, such as (اصغر عدد64, اكبر عدد64) (smallest, largest), with two fields or more (since 0.14.0).
  • You write it as the function’s return type, and return its value in parentheses: ارجع (ص, ك).
  • Destructuring: ص, ك = حدود(درجات) puts each field into a name, in order, and _ is for a field you do not want.
  • Or you keep the whole tuple under one name and read a field with a dot: ح.اكبر. اطبع(ح) prints the fields with their names.
The smallest and the largest mark
# حدود قائمة درجات: أصغرها وأكبرها في نداء واحد
داله حدود(درجات قائمة[عدد64]) (اصغر عدد64, اكبر عدد64):
ص = درجات[0]
ك = درجات[0]
لكل د في درجات:
اذا د < ص:
ص = د
اذا د > ك:
ك = د
ارجع (ص, ك)
درجات قائمة[عدد64] = [72, 95, 64, 88]
ص, ك = حدود(درجات)
اطبع("أصغر درجة: ", ص, "، وأكبر درجة: ", ك)
ح = حدود(درجات)
اطبع(ح)
اطبع("المدى: ", ح.اكبر - ح.اصغر)
_, اعلى = حدود([3, 9, 5])
اطبع("الأعلى وحده: ", اعلى)
حرر(درجات)
Output recorded from the compilermeem صفوف_حدود.م · meem 0.17.3+434e13f
أصغر درجة: 64، وأكبر درجة: 95(اصغر: 64, اكبر: 95)المدى: 31الأعلى وحده: 9

A tuple can also be a list element, and لكل (for each) unpacks it on every round:

A list of tuples
# نقاط على خريطة: قائمة صفوف، ولكل بتفكيك
مواقع قائمة[(اسم نص, س عدد64, ص عدد64)] = [("البيت", 0, 0), ("المدرسة", 3, 4), ("السوق", -2, 5)]
لكل (اسم, س, ص) في مواقع:
اطبع(اسم, ": ", س, "، ", ص)
حرر(مواقع)
Output recorded from the compilermeem صفوف_مواقع.م · meem 0.17.3+434e13f
البيت: 0، 0المدرسة: 3، 4السوق: -2، 5

Write a function ملخص (summary) that takes a list of ages and returns a tuple with their total (عدد64) and their average (كسر64), then print both.

Show the solution
Solution
# مجموع الأعمار ومعدلها في نداء واحد
داله ملخص(اعمار قائمة[عدد64]) (مجموع عدد64, معدل كسر64):
م = 0
لكل ع في اعمار:
م += ع
ارجع (م, كسر64(م) / كسر64(طول(اعمار)))
اعمار قائمة[عدد64] = [12, 15, 9, 20]
م, ع = ملخص(اعمار)
اطبع("المجموع: ", م)
اطبع("المعدل: ", ع)
حرر(اعمار)
Output recorded from the compilermeem صفوف_حل.م · meem 0.17.3+434e13f
المجموع: 56المعدل: 14.0

The number of names in the destructuring does not match the number of fields in the tuple (E0490):

Causes the error
داله نقطة() (س عدد64, ص عدد64):
ارجع (3, 4)
ا, ب, ج = نقطة()
Output recorded from the compilermeem صفوف_خطأ.م · meem 0.17.3+434e13f
​[خطأ دلالي E0490] سطر 3:1 - التفكيك فيه 3 أسماء والصف '(س عدد64, ص عدد64)' فيه 2 حقول   3 | ا, ب, ج = نقطة()     | ^  تلميح: اسم لكل حقل بالترتيب (س, ص)، و_ لحقل لا تريده.

Exit code: 2

In the error catalog: E0490

The fix: one name for each field, and _ for what you do not want (ا, _ = نقطة()). Note also that two tuples are not compared with == directly (E0147); compare their fields.

Types: tuples and multiple return values · Functions · Structs