4. Functions¶
A function is a piece of work with a name. You write it once, then use it whenever you
need it, with different values each time. So far you have used a function someone else
wrote, اطبع. In this lesson you write your own.
A first function¶
دالة(«function») starts the definition, followed by the function's name, hereرحّب(«welcome»).- Between the brackets are the parameters: what the function needs to work. Each has a
name and a type:
اسم: نص(«name: text»). - What's between
{ }is the function's body. It only runs when you call the function:رحّب("مريم").
A function that returns a value¶
Most functions don't print. They work something out and give it back to the caller:
دالة مساحة_مستطيل(الطول: عشري، العرض: عشري): عشري {
أرجع الطول * العرض
}
ثابت م = مساحة_مستطيل(4، 2.5)
اطبع("المساحة:"، م)
اطبع("مساحة غرفتين:"، مساحة_مستطيل(3، 3) * 2)
: عشري after the brackets is the type of what the function returns, and أرجع («return»)
ends the function and gives back the value.
When the body is a single line, write it after =:
Defaults and named arguments¶
Give a parameter a default value, and mentioning it becomes optional. When calling, you can
also name a parameter, which makes the call clearer. Here is a final price with tax
(الضريبة) and discount (الخصم):
دالة سعر_نهائي(السعر: عشري، الضريبة: عشري = 0.15، الخصم: عشري = 0): عشري {
ثابت بعد_الخصم = السعر * (1 - الخصم)
أرجع (بعد_الخصم * (1 + الضريبة)).تقريب(2)
}
اطبع(سعر_نهائي(100))
اطبع(سعر_نهائي(100، الخصم: 0.2))
اطبع(سعر_نهائي(100، الضريبة: 0، الخصم: 0.5))
Ḍād checks every call before running. If you give a value of the wrong type, or misspell the function's name, it tells you, and suggests the right name:
خطأ [السطر 4، العمود 11]: المعامل «س» في «مربع»: توقعت قيمة من النوع «صحيح» لكن وجدت «نص»
خطأ [السطر 5، العمود 6]: «مربعات» غير معرّف؛ هل تقصد «مربع»؟
The first message says the parameter «س» expected a صحيح but got a نص; the second says
«مربعات» isn't defined, and asks «did you mean «مربع»?».
Functions are values too¶
You can give a function to another function. An anonymous function is written between
{ }. If it takes one value, that value is called هو («it») inside; otherwise write the
names of its values before =>:
دالة طبّق_مرتين(د: (صحيح) => صحيح، س: صحيح): صحيح = د(د(س))
اطبع(طبّق_مرتين({ هو + 10 }، 1))
اطبع(طبّق_مرتين({ هو * هو }، 3))
ثابت اجمع = { أ، ب => أ + ب }
اطبع(اجمع(2، 3))
طبّق_مرتين («apply twice») takes a function د and a number. You'll use anonymous
functions a lot with lists in the next lesson.
A function that calls itself¶
A function can call itself, as long as it comes to an end:
Exercise¶
- Write a function
أكبر(أ: صحيح، ب: صحيح): صحيحthat returns the larger of the two numbers. - Write a function
حرارة_فهرنهايت(مئوية: عشري): عشريthat converts a temperature from Celsius to Fahrenheit: F = C × 9 ÷ 5 + 32. Try it on 0, 100 and 37.
Solution
Next: Lists and maps