We declare values and functions in F# with the let
-keyword. Y equals 100. We introduce a binding to the value 100 to the identifier Y. We cannot change the meaning of Y later.
With the mutable keyword, we create mutable values (variables). These can be changed as a program executes. With let (part of the lightweight syntax) we also declare functions.
This first example uses the "mutable" keyword on a variable. We bind the identifier "number" to the value 100 and then reassign "number" to 200.
// Create a mutable variable. let mutable number = 100 printfn "%d" number // Reassign the variable to another value. number <- 200 printfn "%d" number100 200
This problem is encountered by many new F# developers. We try to assign a value that is not mutable. We can fix this by adding a mutable keyword to "color."
let color = "green" printfn "%s" color // This causes an error. color <- "blue" printfn "%s" colorerror FS0027: This value is not mutable
Consider this program. We do not reassign any variable. Instead we just use two separate let
-values. The meaning of this program is easy to understand.
// Use two identifiers for the values. let color1 = "magenta" printfn "%s" color1 let color2 = "crimson" printfn "%s" color2magenta crimson
The F# language uses a lightweight syntax. This considers indentation. It requires the "let" keyword for function declarations.
string
parameter, and returns a string
(a type inferred by the compiler).let
-keyword.// Use let keyword to create a function that receives a string. // ... It returns another string. let greeting (name : string) = "Hi " + name.ToUpper() + "," // Call the function and print its result. printfn "%s" (greeting "visitor") printfn "How are you?"Hi VISITOR, How are you?
Sometimes a function is long and complex. Having temporary (intermediate) values makes it easier to reason about. We can use let
-values inside a "let" function.
let combineStrings left right = // Create a temporary string based on the first argument. let value1 = "[" + left + "]" // Based on the second argument. let value2 = "{" + right + "}" // Return another string. // ... This is not optimally fast. value1 + "..." + value2 // Call the function with two string arguments. let result = combineStrings "cat" "dog" printfn "%s" result[cat]...{dog}
Sometimes a let statement spans multiple lines. This is not easy to comment out with single-line comments. But with a block comment we can temporarily erase it.
(* let modify x = List.map (fun y -> y * 2) x |> List.sum *)
Indentation is important in F#. We must line up statements in the correct position when using lightweight syntax.
Special features like inferred types make F# fast to write and easy to understand. With "let" we solve many problems: we specify values, variables and functions.