W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
聯(lián)合(Unions)或差別聯(lián)合(discriminated unions)允許您構(gòu)建表示明確定義的一組選擇的復(fù)雜數(shù)據(jù)結(jié)構(gòu)。 例如,您需要構(gòu)建一個achoicevariable的實現(xiàn),它具有兩個值yes和no。 使用Unions工具,你可以自由設(shè)計它。
差別聯(lián)合使用下面的語法定義
type type-name = | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...] | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...] ...
簡單的實現(xiàn),選擇,示例如下
type choice = | Yes | No
下面的示例使用類型選擇
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()
當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出
x: Yes y: No
以下示例顯示了在高電平或低電平時置位的電壓狀態(tài)的實現(xiàn)
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()
當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出
Switch on state: High Switch off state: Low Toggle off: High Toggle the Changed state: Low
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)
當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出
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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: