F# Basic Syntax Cheat Sheet

Words
41
Reading
1 min
Listen
Play
9y

I have not had much time for my Roguelike so thought I would throw together a quick cheat sheet of some basic F# syntax to help people understand some of the code

// Declare value binding

let unitValue = ()          // unit
let anInt = 42              // int value
let aString = "blah"        // string value
let aFloat = 4.2            // float value
let aDouble = 4.2m          // double value

// Declare functions

let noArgs () = 42          // No such thing as no arg function unit -> int
let add1 x = x + 1          // One arg function
let add x y = x + y         // Two arg function

// Generic functions

let inline genAdd x y = x + y 

// Function calling

let result0 = noArgs ()     // = 42
let result1 = add1 41       // = 42
let result2 = add 40 2      // = 42

// Error add takes ints as first use was ints
//let error = add 4.0 5.0

// Can use for anything with + as inlined
let intAdd = genAdd 5 6
let floatAdd = genAdd 5.0 6.0

// Partial application

let anotherAdd1 = add 1     // = int -> int
let result = anotherAdd1 41 // = 42

// Value piping

let piped1 = 40 |> add 2    // = 42
let piped2 = add <| 2 <| 40 // = 42

// Tuples

let tuple = (4, "2")        // (int * string)
let four = fst tuple        // int
let two = snd tuple         // string
let (first, second) = tuple // Extract both into bindings
let (f, _) = tuple          // Extract the first value
let (_, S) = tuple          // Extract the second value

// Records

type record = {id: int; name: string}
let aRecord = {id = 5; name = "Bill"}
let id = aRecord.id         // = 5
let name = aRecord.name     // = "Bill"
let updated = {aRecord with name = "Bob"}

// Unions

type nullable =
    | Value of int
    | Null

let aValue = Value 5        // Value of 5
let nothing = Null          // Null (Not null as in C but type)

// Pattern matching

let extract x =
    match x with
    | Value y -> y
    | Null -> 0

let extractedValue = extract aValue // = 5
let extractedNull = extract nothing // = 0

Feel free to ask any questions

Happy coding

Woz

F# Basic Syntax Cheat Sheet | Ecency