سلام درود خدمت همراهان همیشگی سایت پی وی لرن . با آموزش زبان برنامه نویسی #F همراهتون هستیم. Discriminated Unions در #F و سینتکس Discriminated Union در #F رو بیان می نماییم.
Discriminated Unions یا Unions در #F به شما امکان ساخت ساختارهای پیچیده داده ها را می دهند که (set of choices) ستی از گزینه های مشخص را مشخص می کنند. برای مثال، شما باید پیاده سازی یک متغیر انتخابی ایجاد کنید که دارای دو مقدار yes و no است. با استفاده از ابزار Unions ، شما می توانید این را طراحی کنید.
Discriminated Unions با استفاده از سینتکس زیر تعریف می شوند:
1 2 3 4 5 | type type-name = | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...] | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...] ... |
پیاده سازی ساده ما ،choice، به صورت زیر خواهد بود.
1 2 3 | type choice = | Yes | No |
مثال زیر از نوع choice استفاده می کند.
1 2 3 4 5 6 7 8 9 10 | type choice = | Yes | No let x = Yes (* creates an instance of choice *) let y = No (* creates another instance of choice *) let main() = printfn "x: %A" x printfn "y: %A" y main() |
هنگامی که شما برنامه را کامپایل و اجرا می کنید، خروجی زیر را تولید می کند.
1 2 | x: Yes y: No |
مثال زیر اجرای مقادیر ولتاژ که یک بیت را بصورت بالا و یا پایین تنظیم می کند، را نشان می دهد.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | type VoltageState = | High | Low let toggleSwitch = function (* pattern matching input *) | High -> Low | Low -> High let main() = let on = High let off = Low let change = toggleSwitch off printfn "Switch on state: %A" on printfn "Switch off state: %A" off printfn "Toggle off: %A" change printfn "Toggle the Changed state: %A" (toggleSwitch change) main() |
هنگامی که شما برنامه را کامپایل و اجرا می کنید، خروجی زیر را تولید می کند.
1 2 3 4 | Switch on state: High Switch off state: Low Toggle off: High Toggle the Changed state: Low |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | type Shape = // here we store the radius of a circle | Circle of float // here we store the side length. | Square of float // here we store the height and width. | Rectangle of float * float let pi = 3.141592654 let area myShape = match myShape with | Circle radius -> pi * radius * radius | Square s -> s * s | Rectangle (h, w) -> h * w let radius = 12.0 let myCircle = Circle(radius) printfn "Area of circle with radius %g: %g" radius (area myCircle) let side = 15.0 let mySquare = Square(side) printfn "Area of square that has side %g: %g" side (area mySquare) let height, width = 5.0, 8.0 let myRectangle = Rectangle(height, width) printfn "Area of rectangle with height %g and width %g is %g" height width (area myRectangle) |
هنگامی که شما برنامه را کامپایل و اجرا می کنید، خروجی زیر را تولید می کند.
1 2 3 | Area of circle with radius 12: 452.389 Area of square that has side 15: 225 Area of rectangle with height 5 and width 8 is 40 |
در این قسمت از آموزش اف شارپ با سینتکس Discriminated Union در #F سینتکس Discriminated Unions در #F آشنا شدیم.