- F# 基礎教程
- F# - 首頁
- F# - 概述
- F# - 環境設定
- F# - 程式結構
- F# - 基本語法
- F# - 資料型別
- F# - 變數
- F# - 運算子
- F# - 決策
- F# - 迴圈
- F# - 函式
- F# - 字串
- F# - 選項
- F# - 元組
- F# - 記錄
- F# - 列表
- F# - 序列
- F# - 集合
- F# - 對映
- F# - 辨別聯合
- F# - 可變資料
- F# - 陣列
- F# - 可變列表
- F# - 可變字典
- F# - 基本 I/O
- F# - 泛型
- F# - 委託
- F# - 列舉
- F# - 模式匹配
- F# - 異常處理
- F# - 類
- F# - 結構體
- F# - 運算子過載
- F# - 繼承
- F# - 介面
- F# - 事件
- F# - 模組
- F# - 名稱空間
F# - 辨別聯合
聯合,或稱為辨別聯合,允許您構建複雜的データ結構,表示定義明確的一組選擇。例如,您需要構建一個選擇變數的實現,該變數具有兩個值 yes 和 no。使用聯合工具,您可以設計此變數。
語法
辨別聯合使用以下語法定義:
type type-name = | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...] | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...] ...
我們對選擇的簡單實現如下所示:
type choice = | Yes | No
以下示例使用型別 choice:
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()
編譯並執行程式後,它會產生以下輸出:
x: Yes y: No
示例 1
以下示例顯示了電壓狀態的實現,該狀態設定高或低位:
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()
編譯並執行程式後,它會產生以下輸出:
Switch on state: High Switch off state: Low Toggle off: High Toggle the Changed state: Low
示例 2
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)
編譯並執行程式後,它會產生以下輸出:
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
廣告