Share via


逐步解說:您的第一個 F# 程式

Visual Studio 2010 包括新的程式設計語言:F#。 F# 是一套多重開發架構語言,除了傳統的物件導向程式設計和 .NET 概念以外,它還支援函式程式設計。 下列範例將介紹其部分功能和語法。 這些範例會示範如何宣告簡單變數、撰寫和測試函式、建立 Tuple 和清單,以及定義和使用類別。

注意事項注意事項

您的電腦可能會在下列說明中,以不同名稱或位置顯示某些 Visual Studio 使用者介面項目。 您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。 如需詳細資訊,請參閱 Visual Studio 設定

若要建立新的主控台應用程式

  1. 在 [檔案] 功能表上,指向 [新增],然後按一下 [專案]。

  2. 如果您在 [範本類別] 窗格中看不到 Visual F#,請按一下 [其他語言],然後按一下 [Visual F#]。 中間的 [範本] 窗格就會列出 F# 範本。

  3. 查看 [範本] 窗格的頂端,確定 [.NET Framework 4] 顯示在 [目標 Framework] 方塊中。

  4. 在範本的清單中,按一下 [F# 應用程式]。

  5. 在 [名稱] 欄位中,輸入專案的名稱。

  6. 按一下 [確定]。

    新專案即會出現於 [方案總管] 中。

若要使用 let 關鍵字來宣告和使用識別碼

  • 將下列程式碼複製並貼入 Program.fs 中。 您就會將每個識別碼 anInt、aString 和 anIntSquared 繫結至某個值。

    let anInt = 5
    let aString = "Hello"
    // Perform a simple calculation and bind anIntSquared to the result.
    let anIntSquared = anInt * anInt
    
    注意事項注意事項

    如果無法使用傳統檢視看見程式碼,請確定主題標題下方小標題中的 [語言篩選條件] 設定為包含 F#。

若要在 F# Interactive 視窗中查看結果

  1. 選取上述程序中的 let 運算式。

  2. 以滑鼠右鍵按一下選取的區域,然後按一下 [傳送到 Interactive]。 或者,按下 ALT+ENTER。

  3. [F# Interactive] 視窗便會開啟並且顯示解譯 let 運算式的結果,如下列各行所示。 這些型別是根據指定的值推斷而得。

    val anInt : int = 5

    val aString : string = "Hello"

    val anIntSquared : int = 25

若要在命令提示字元視窗中查看結果

  1. 將下列各行加入至 Program.fs

    System.Console.WriteLine(anInt)
    System.Console.WriteLine(aString)
    System.Console.WriteLine(anIntSquared)
    
  2. 按下 CTRL+F5 執行程式碼。 此時會出現 [命令提示字元] 視窗,其中包含下列值。

    5

    Hello

    25

    您可以將滑鼠指標停留在上述 WriteLine 陳述式的識別碼名稱 anInt、aString 和 anIntSquared 上,藉以確認推斷的型別。

若要定義和執行函式

  1. 使用 let 運算式來定義計算平方函式,如下列程式碼所示。 此函式具有一個參數 n,而且會傳回傳送至 n 之引數的平方。

    let square n = n * n
    // Call the function to calculate the square of anInt, which has the value 5.
    let result = square anInt
    // Display the result.
    System.Console.WriteLine(result)
    
  2. 按下 CTRL+F5 執行程式碼。 顯示的結果為 25。

  3. 遞迴函式需要 let rec 運算式。 下列範例會定義一個計算參數 n 之階乘的函式。

    let rec factorial n = 
        if n = 0 
        then 1 
        else n * factorial (n - 1)
    System.Console.WriteLine(factorial anInt)
    
  4. 按下 CTRL+F5 執行函式。 顯示的結果為 120,也就是 5 的階乘。

若要建立集合:清單和 Tuple

  1. 彙總值的其中一種方式是使用 Tuple,如下列程式碼所示。

    let turnChoices = ("right", "left")
    System.Console.WriteLine(turnChoices)
    // Output: (right, left)
    
    let intAndSquare = (anInt, square anInt)
    System.Console.WriteLine(intAndSquare)
    // Output: (5,25)
    
  2. 彙總值的另一種方式是使用清單,如下列程式碼所示。

    // List of best friends.
    let bffs = [ "Susan"; "Kerry"; "Linda"; "Maria" ] 
    

    使用 "cons" 運算子 (::),將新的好朋友加入至清單。 請注意,此作業不會變更 bffs 的值。 bffs 的值是不可變的,而且無法變更。

    // Bind newBffs to a new list that has "Katie" as its first element.
    let newBffs = "Katie" :: bffs
    

    使用 printfn 來顯示清單。 函式 printfn 會顯示結構化值中所包含的個別項目。

    printfn "%A" bffs
    // Output: ["Susan"; "Kerry"; "Linda"; "Maria"]
    printfn "%A" newBffs
    // Output: ["Katie"; "Susan"; "Kerry"; "Linda"; "Maria"]
    
  3. 您可以按下 CTRL+F5,或選取某個程式碼區段,然後按下 ALT+ENTER,藉以檢視結果。

若要建立和使用類別

  1. 下列程式碼會建立具有兩個屬性的 Person 類別:Name 和 Age。 Name 是唯讀屬性。 其值是不可變的,如同函式程式設計中大部分的值。 必要時,您可以在 F# 中建立可變的值,但是必須將它們明確定義成可變的值。 在下列類別定義中,Age 的值會儲存在可變的區域變數 internalAge 中。 您可以變更 internalAge 的值。

    // The declaration creates a constructor that takes two values, name and age.
    type Person(name:string, age:int) =
        // A Person object's age can be changed. The mutable keyword in the
        // declaration makes that possible.
        let mutable internalAge = age
    
        // Declare a second constructor that takes only one argument, a name.
        // This constructor calls the constructor that requires two arguments,
        // sending 0 as the value for age.
        new(name:string) = Person(name, 0)
    
        // A read-only property.
        member this.Name = name
        // A read/write property.
        member this.Age
            with get() = internalAge
            and set(value) = internalAge <- value
    
        // Instance methods.
        // Increment the person's age.
        member this.HasABirthday () = internalAge <- internalAge + 1
    
        // Check current age against some threshold.
        member this.IsOfAge targetAge = internalAge >= targetAge
    
        // Display the person's name and age.
        override this.ToString () = 
            "Name:  " + name + "\n" + "Age:   " + (string)internalAge
    
    
  2. 若要測試類別,請宣告兩個 Person 物件、進行一些變更,然後顯示結果,如下列程式碼所示。

    // The following let expressions are not part of the Person class. Make sure
    // they begin at the left margin.
    let person1 = Person("John", 43)
    let person2 = Person("Mary")
    
    // Send a new value for Mary's mutable property, Age.
    person2.Age <- 15
    // Add a year to John's age.
    person1.HasABirthday()
    
    // Display results.
    System.Console.WriteLine(person1.ToString())
    System.Console.WriteLine(person2.ToString())
    // Is Mary old enough to vote?
    System.Console.WriteLine(person2.IsOfAge(18))
    

    下列各行隨即顯示。

    Name: John

    Age: 44

    Name: Mary

    Age: 15

    False

若要檢視 F# 教學課程中的其他範例

  1. 在 [檔案] 功能表上,指向 [新增],然後按一下 [專案]。

  2. 如果您在 [範本類別] 窗格中看不到 Visual F#,請按一下 [其他語言],然後按一下 [Visual F#]。 中間的 [範本] 窗格就會列出 F# 範本。

  3. 查看 [範本] 窗格的頂端,確定 [.NET Framework 4] 顯示在 [目標 Framework] 方塊中。

  4. 在範本的清單中,按一下 [F# 教學課程]。

  5. 按一下 [確定]。

  6. 教學課程隨即出現在 [方案總管] 中。

後續步驟

如需函式程式設計和其他範例的詳細資訊,請參閱當做優先使用值的函式 (F#)。 如需 Tuple、清單、let 運算式、函式定義、類別、成員和許多其他主題的詳細資訊,請參閱 F# 語言參考

請參閱

概念

Visual F# 2010 的新功能

當做優先使用值的函式 (F#)

其他資源

Visual F#

F# 語言參考