در #F سه نوع حلقه تکرار وجود دارد. مفهوم حلقههای تکرار در #F مانند سایر زبانهای برنامه نویسی است. در این جا فقط به syntax و نوع کد نویسی اشاره خواهیم داشت.
انواع حلقههای تکرار
- حلقه تکرار for in
- حلقه تکرار for to
- حلقه تکرار while do
در ادامه به بررسی و پیاده سازی مثال برای هر سه حلقه میپردازیم
#1 حلقه for ساده
let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
printfn "%d" i
خروجی:
#2حلقه for با تعداد پرش دو( 1 تا 10 با تعداد پرش 2
) for i in 1 .. 2 .. 10 do
printf "%d " i
خروجی
#3 حلقه for با استفاده از محدوده کاراکتر ها
for c in 'a' .. 'z' do
printf "%c " c
خروجی
a b c d e f g h i j k l m n o p q r s t u v w x y z
#4 حلقه for به صورت شمارش معکوس
for i in 10 .. -1 .. 1 do
printf "%d " i
خروجی :
#5حلقه for که شروع و اتمام محدوده آن به صورت عبارت است.
let beginning x y = x - 2*y
let ending x y = x + 2*y
for i in (beginning x y) .. (ending x y) do
printf "%d " i
خروجی مثال بالا با ورودیهای 10 و 4 به صورت زیر خواهد بود
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#6 حلقه for to
for i = 1 to 10 do
printf "%d " i
خروجی
#7 حلقه for to به صورت شمارش معکوس
for i = 10 downto 1 do
printf "%d " i
خروجی
#8 حلقه for to با استفاده از محدوده شروع و اتمام به صورت عبارت
for i = (beginning x y) to (ending x y) do
printf "%d " i
خروجی مثال بالا برای ورودیهای 10 و 4 به صورت زیر است
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#9 حلقه while do
ساختار کلی آن به صورت زیر است.
while test-expression do
body-expression
#10مثال کامل از حلقه while do
open System
let main() =
let password = "monkey"//شناسه برای مقدار رمز عبور
let mutable guess = String.Empty// شناسه برای حدس رمز عبور
let mutable attempts = 0//تعداد دفعات تست
while password <> guess && attempts < 3 do// تا زمانی که رمز عبور با حدس آن برابر نیست و تعداد دفعات تکرار کمتر از سه است
Console.Write("What's the password? ")//چاپ پیغام در خروجی
attempts <- attempts + 1//مقدار دفعات یکی افزایش مییابد
guess <- Console.ReadLine()// حدس رمز عبور از ورودی دریافت میشود
if password = guess then// اگر رمز عبور با حدس آن یکی بود
Console.WriteLine("You got the password right!")// پیغام موفقیت
else
Console.WriteLine("You didn't guess the password")//پیغام عدم موفقیت
Console.ReadKey(true) |> ignore//منتظر ورودی برای خروج از برنامه
تنها نکته قابل ذکر در مثال بالا استفاده از mutable keyword برای تعریف شناسه attempts است. (طبق توضیحات فصل قبل) به دلیل اینکه تعداد دفعات تکرار برای ما مهم است و نمیخواهیم در هر محدوده این مقدار به حالت قبلی خود بازگردد از mutable استفاده کردیم.