Fsharp Cheatsheet
Fsharp Cheatsheet
Comments
Block comments are placed between (* and *). Line
comments start from // and continue until the end of the line.
Functions
The let keyword also defines named functions.
let negate x = x * -1
let square x = x * x
let print x = printfn "The number is: %d" x
Strings
F# string type is an alias for System.String type.
/// Create a string using string concatenation
let hello = "Hello" + " World"
Lists
let squareNegateThenPrint =
square >> negate >> print
Recursive functions
let poem =
"The lesser world was daubed\n\
By a colorist of modest skill\n\
A master limned you in the finest inks\n\
And with a fresh-cut quill."
val
val
val
val
s : float32 = 4.14f
f : float = 4.14
d : decimal = 0.7833M
bi : System.Numerics.BigInteger = 9999
Arrays
Arrays are fixed-size, zero-based, mutable collections of
consecutive data elements.
Sequences
Collections
A list is an immutable collection of elements of the same type.
let squareNegateThenPrint x =
print (negate (square x))
let sign x =
match x with
| 0 -> 0
| x when x < 0 -> -1
| x -> 1
and odd x =
if x = 1 then true
else even (x - 1)
Pattern Matching
Pattern matching is often facilitated through match keyword.
let rec fib n =
match n with
| 0 -> 0
| 1 -> 1
| _ -> fib (n - 1) + fib (n - 2)
In order to match sophisticated inputs, one can use when to
create filters or guards on patterns:
Exceptions
let divideFailwith x y =
if y = 0 then
failwith "Divisor cannot be zero."
else x / y
Discriminated Unions
let divide x y =
try
Some (x / y)
with :? System.DivideByZeroException ->
printfn "Division by zero!"
None
The try/finally expression enables you to execute clean-up
code even if a block of code throws an exception. Heres an
example which also defines custom exceptions.
exception InnerError of string
exception OuterError of string
let handleErrors x y =
try
try
if x = y then raise (InnerError("inner"))
else raise (OuterError("outer"))
with InnerError(str) ->
printfn "Error1 %s" str
finally
printfn "Always print this."
type Tree<T> =
| Node of Tree<T> * T * Tree<T>
| Leaf
This example is a basic class with (1) local let bindings, (2)
properties, (3) methods, and (4) static members.
type Dog() =
inherit Animal()
member __.Run() =
base.Rest()
type Animal() =
member __.Rest() = ()
// Create a DU value
let orderId = Order "12"
Active Patterns
Compiler Directives
let (|Even|Odd|) i =
if i % 2 = 0 then Even else Odd
#load "../lib/StringParsing.fs"
let testNumber i =
match i with
| Even -> printfn "%d is even" i
| Odd -> printfn "%d is odd" i
Parameterized active patterns:
let (|DivisibleBy|_|) by n =
if n % by = 0 then Some DivisibleBy else None
#if INTERACTIVE
let path = __SOURCE_DIRECTORY__ + "../lib"
#else
let path = "../../../lib"
#endif