基礎

基礎 在 F#

1 個練習

關於 基礎

在 F# 中,任何具有型別且能被定義的東西都稱為_值_。這包括布林值、整數和陣列,也包含函式。整數值是由一個或多個(連續的)數字定義,並支援預設的數學運算子。

將值指定給名稱的動作稱為_繫結_。繫結是不可變的,因此類似於其他語言中的常數。繫結是使用let關鍵字定義的。

由於 F# 是靜態型別的語言,每個繫結都有型別。對大多數繫結來說,指定型別是選用的,因為 F# 的_型別推斷_通常可以根據它們的值推斷出型別。

// Automatically inferred type
let fingers = 10

函式也是一般的繫結,只是帶有一個或多個參數。函式會自動回傳它的最後一個運算式。型別推斷對大多數函式也適用,它會分析函式被呼叫時帶了哪些值,以及函式回傳什麼值。

// Automatically inferred types for parameters and return type
let add x y = x + y

呼叫函式的方式,是指定函式名稱,並為函式的每個參數傳入引數。

let five = add 2 3

如果無法推斷繫結的型別,編譯器會回報錯誤。若要修正,請明確指定繫結的型別。

// Explicit type annotation
let fingers: int = 10

// Explicit type annotation (also for parameters)
let add (x: int) (y: int): int = x + y

F# 中的繫結只能在定義_之後_使用。在繫結定義之前就使用它,會導致編譯錯誤。

// Compile error as the add binding has not yet been defined
// let seven = add 3 + 4

let add x y = x + y

顯著空白用來定義作用域,做法是相對於宣告繫結的那一行,用空格將程式碼縮排。預設慣例是使用 4 個空格縮排。

let toes =
    let left = 5
    let right = 5
    left + right

let multiplyPlusTwo x y =
    let product = x * y
    product + 2

// Trying to access the left, right or product bindings
// here would result in a compile error

F# 的繫結(包含函式)通常會組織在模組中。模組會將相關的功能群組在一起,並使用module關鍵字定義。模組定義必須放在它的繫結之前:

module Calculator

let pi = 3.14

let add x y = x + y

F# 支援兩種註解。單行註解前面會加上//,多行註解則插入在(*與*)之間。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 基礎