Assignment
let x = 10
let y = if x> 10 then 1 else 2
let mutable z = 1
z <- z + 1
Notes:
1. Value of x cannot be changed. So we refer x as a value instead of a variable.
2. z is mutable
3. Use <- operator to change the value of a mutable value
4. Specifying a type is not necessary as the type will be inferred by the RHS value.
Function Declaration
let f n = 10 * n + 2
let f a b = a * 2 + b
Notes:
1. No parenthesis is surrounding the argument
2. No comma to separate arguments
Calling a function
let x = f 10
let y = f 10 + 1
Notes:
1. No parenthesis is surrounding the argument
Recursion
let rec f n = if n > 0 then (f n-1) * 2 else 1
Notes:
1. rec prefix must be used to allow a function to call itself.
Looping
for i = 1 to 10 do printfn i
for i = 1 to 10 do
printf "Hello,"
printfn "World"
This concludes a general introduction to the basic syntax of F#.
Function Declaration
let f n = 10 * n + 2
let f a b = a * 2 + b
Notes:
1. No parenthesis is surrounding the argument
2. No comma to separate arguments
Calling a function
let x = f 10
let y = f 10 + 1
let z = f (x + 10)
Notes:
1. No parenthesis is surrounding the argument
2. y = x +1 as function calling has a higher precedence than binary operators
3. Parenthesis is used to change the association
Recursion
let rec f n = if n > 0 then (f n-1) * 2 else 1
Notes:
1. rec prefix must be used to allow a function to call itself.
2. Recursive function must have a terminal case (e.g. n = 0 -> 1).
Looping
for i = 1 to 10 do printfn i
for i = 1 to 10 do
printf "Hello,"
printfn "World"
Notes:
1. printf and printfn are built-in functions for printing to console. printfn terminates the line with a carriage return
2. Indentation is significant to define the boundary of the block (so no next statement is required)
Conditional
1. printf and printfn are built-in functions for printing to console. printfn terminates the line with a carriage return
2. Indentation is significant to define the boundary of the block (so no next statement is required)
Conditional
let f n = if n > 10 then
let m = 20
let p = m + n
n
else
n - 1
Notes:
1. Indentation is used to define the block
2. Last expression within a block will be used as the return value
3. If the else part is not defined, compilation error will be resulted
This concludes a general introduction to the basic syntax of F#.
No comments:
Post a Comment