15. Enums
To define an enum for a known set of fixed values (seasons, directions, the states of a game), and to handle all its values with حالات (match).
Explanation
Section titled “Explanation”تعداد الاسم:(enum) at the top level, then one member per line. The name is a new type, and a member is writtenالاسم.العضو.- A member’s number is its position from 0, and
عدد64(العضو)gives it. لكل ف في فصل:goes through the members in order.حالاتon an enum must name every member, or addحاله _:for the rest. Forgetting a member is a compile error, so no case slips past you.
تعداد فصل: شتاء ربيع صيف خريف
داله وصف(ف فصل) نص: حالات ف: حاله فصل.شتاء: ارجع "بارد" حاله فصل.ربيع: ارجع "معتدل" حاله فصل.صيف: ارجع "حار" حاله فصل.خريف: ارجع "متقلب"
لكل ف في فصل: اطبع(ف, " (", عدد64(ف), "): ", وصف(ف))Enums with a payload (since 0.15.0): a member has fields in parentheses, so each member carries its own data, and حاله شكل.دائرة(نق): in حالات unpacks them by name. Details in enums:
تعداد شكل: دائرة(نق كسر64) مستطيل(ع كسر64, ط كسر64) نقطة_فقط
داله مساحة(ش شكل) كسر64: حالات ش: حاله شكل.دائرة(نق): ارجع 3.14159 * نق * نق حاله شكل.مستطيل(ع, ط): ارجع ع * ط حاله شكل.نقطة_فقط: ارجع 0.0 ارجع 0.0
اطبع(مساحة(شكل.دائرة(1.0)))اطبع(مساحة(شكل.مستطيل(3.0, 4.0)))اطبع(مساحة(شكل.نقطة_فقط))Exercise
Section titled “Exercise”A traffic light: an enum اشارة (أحمر red, أصفر yellow, أخضر green), and a function التالية that gives the next light (red ← green ← yellow ← red). Print five steps starting from red.
Show the solution
تعداد اشارة: احمر اصفر اخضر
داله التالية(ا اشارة) اشارة: حالات ا: حاله اشارة.احمر: ارجع اشارة.اخضر حاله اشارة.اخضر: ارجع اشارة.اصفر حاله اشارة.اصفر: ارجع اشارة.احمر
ا = اشارة.احمرلكل خطوة في مدى(0, 5): اطبع(خطوة, ": ", ا) ا = التالية(ا)Common mistakes
Section titled “Common mistakes”A حالات that does not name every member:
تعداد اتجاه: شمال جنوب
ا = اتجاه.شمالحالات ا: حاله اتجاه.شمال: اطبع("إلى الأعلى")Exit code: 2
In the error catalog: E0388
The fix: add حاله اتجاه.جنوب:, or add حاله _: for the rest.
See also
Section titled “See also”Enums in the reference · Statements: حالات