Write a program in F#
A zero project can be written in F#. It's an .fsproj with the same SDK, and builds the same kind of
small native program, for the same targets. Records, unions, pattern matching, closures, lists,
seq { }, Map, Set, decimal and printf work. The program has no .NET runtime and no garbage collector,
the same as a C# zero program.
This guide uses the .NET SDK packages (Install with dotnet), from version 0.12.0: 0.11.0 and earlier have no F#. Its code comes from the SDK's tests, which build each program and check what it prints against .NET's F#.
Make a project
The templates make F# projects with -lang F#:
dotnet new zero -lang F# -o Hello
dotnet new zerolib -lang F# -o Shapes
<Project Sdk="ZeroCSharp.Sdk/0.14.0">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
</Project>
Build and run it as a C# zero project: dotnet build, dotnet run, dotnet publish, and
-p:ZeroTarget=win-x64 (or linux-arm64, osx-arm64) for another target. The F# compiler is the
one in your .NET SDK; the project compiles against the package's own small FSharp.Core, not the
NuGet one.
Write the program
Top-level code is the program, as in a script:
let greet name = "Hello, " + name + "!"
Out.Line(greet "top-level F#")Or mark a function [<EntryPoint>], which gets the arguments and returns the exit code. Types and
functions from earlier files in the project work as usual:
module Shapes
type Shape =
| Circle of radius: float
| Rect of width: float * height: float
type Point = { X: int; Y: int }
let area shape =
match shape with
| Circle r -> 3.0 * r * r
| Rect (w, h) -> w * h
let rec sum xs =
match xs with
| [] -> 0
| x :: rest -> x + sum rest
let rec map f xs =
match xs with
| [] -> []
| x :: rest -> f x :: map f restmodule Program
open Shapes
[<EntryPoint>]
let main argv =
Out.Line("args: ", int64 argv.Length)
let tens = [ 1; 2; 3; 4 ] |> map (fun x -> x * 10)
Out.Line("sum: ", int64 (sum tens))
let same = { X = 1; Y = 2 } = { X = 1; Y = 2 }
Out.Line(if same then "records equal" else "records differ")
Out.Write "area: "
Out.Write(area (Rect(2.0, 3.5)))
Out.Line()
Out.Line("F# " + "zero")
7Out, In, File and the rest of the library are there, as in C#. Records and unions compare and
hash by their contents, as in .NET.
Print with printf
printf, printfn, eprintfn, sprintf, failwithf and interpolated strings work, with widths,
flags and precision:
let name = "zero"
let n = 42
printfn "Hello, %s! %d" name n
printfn "%5d|%-5d|%05d|%+d|%x|%X|%o|%B" 42 42 42 42 255 255 8 5
printfn "%d %x %u" -7 -1 3000000000u
printfn "%f %.2f %e %g %g" 3.14159 2.5 12345.678 0.0001 1e20
printfn "%c %b %O %s" 'z' true (box 3) (string 2.5)
let s = sprintf "%s-%i" "a" -7
printfn "%s" s
printfn $"interpolated {n} and %d{n * 2} and {name}"
name: stringn: intprintfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
box: 'T -> objnullBoxes a strongly typed value. The value to box. The boxed object. let x: int = 123 let obj1 = box x // obj1 is a generic object type unbox<int> obj1 // Evaluates to 123 (int) unbox<double> obj1 // Throws System.InvalidCastException
string: 'T -> stringConverts the argument to a string using ToString. For standard integer and floating point values and any type that implements IFormattable, ToString conversion uses CultureInfo.InvariantCulture. The input value. The converted string. string 'A' // evaluates to "A" string 0xff // evaluates to "255" string -10 // evaluates to "-10"
s: stringsprintf: Printf.StringFormat<'T> -> 'TPrint to a string using the given format. The formatter. The formatted result. See Printf.sprintf (link: ) for examples.
%A isn't there: it shows a value by reflection, which zero mode doesn't have, and the compiler
refuses it. %O calls ToString.
A function that takes a format and passes it on must be inline, as printf's own functions are.
The compiler then works out the arguments at each call:
// A wrapper taking the format: inline, as printf's own functions are.
let inline count format =
Printf.ksprintf (fun (text: string) -> text.Length) format
printfn "length %d" (count "%s%s" "ab" "cd")
let inline log format =
Printf.ksprintf (fun (text: string) -> Out.Line("log: " + text)) format
log "%d items, %s" 3 "ok"Use lists, sequences, maps and sets
The List, Array, Seq, Map, Set and String modules have FSharp.Core's functions, with the
same results. Arrays and strings are sequences too:
type Item = { Name: string; Price: float; Qty: int }
let items =
[ { Name = "apple"; Price = 0.5; Qty = 10 }
{ Name = "pear"; Price = 0.75; Qty = 4 }
{ Name = "plum"; Price = 0.25; Qty = 0 } ]
let inStock = items |> List.filter (fun i -> i.Qty > 0)
let worth = inStock |> List.sumBy (fun i -> i.Price * float i.Qty)
printfn "%d in stock, worth %.2f" inStock.Length worth
let byName = items |> List.map (fun i -> i.Name, i) |> Map.ofList
printfn "%s" (String.concat ", " (Map.keys byName))
match Map.tryFind "pear" byName with
| Some pear -> printfn "pears: %d" pear.Qty
| None -> printfn "no pears"
Zero_450-how-to_022-write-fsharp.md_page.ItemName: stringstringAn abbreviation for the CLI type . Basic Types
Price: floatfloatAn abbreviation for the CLI type . Basic Types
Qty: intintAn abbreviation for the CLI type . Basic Types
items: Item listinStock: Item list(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Microsoft.FSharp.Collections.ListModuleContains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide.
filter: ('T -> bool) -> 'T list -> 'T listReturns a new collection containing only the elements of the collection for which the given predicate returns "true" The function to test the input elements. The input list. A list containing only the elements that satisfy the predicate. let input = [1, "Luke"; 2, "Kirk"; 3, "Kenobi"; 4, "Spock"] let isEven x = 0 = x % 2 let isComingFromStarTrek (x,_) = isEven x input |> List.filter isComingFromStarTrek Evaluates to [(2, "Kirk"); (4, "Spock")] This is an O(n) operation, where n is the length of the list.
i: Item(>): 'T -> 'T -> boolStructural greater-than The first parameter. The second parameter. The result of the comparison. 5 > 1 // Evaluates to true 5 > 5 // Evaluates to false (1, "a") > (1, "z") // Evaluates to false
worth: floatsumBy: ('T -> ^U) -> 'T list -> ^UReturns the sum of the results generated by applying the function to each element of the list. The function to transform the list elements into the type to be summed. The input list. The resulting sum. let input = [ "aa"; "bbb"; "cc" ] input |> List.sumBy (fun s -> s.Length) Evaluates to 7. This is an O(n) operation, where n is the length of the list.
(*): ^T1 -> ^T2 -> ^T3Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48
float: ^T -> floatConverts the argument to 64-bit float. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Double.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted float float 'A' // evaluates to 65.0 float 0xff // evaluates to 255.0 float -10 // evaluates to -10.0
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
Length: intGets the number of items contained in the list
byName: Map<string,Item>map: ('T -> 'U) -> 'T list -> 'U listBuilds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The function to transform elements from the input list. The input list. The list of transformed elements. let inputs = [ "a"; "bbb"; "cc" ] inputs |> List.map (fun x -> x.Length) Evaluates to [ 1; 3; 2 ] This is an O(n) operation, where n is the length of the list.
Microsoft.FSharp.Collections.MapModuleContains operations for working with values of type .
ofList: ('Key * 'T) list -> Map<'Key,'T>Returns a new map made from the given bindings. The input list of key/value pairs. The resulting map. This is an O(n log n) operation, where n is the length of the list. let input = [ (1, "a"); (2, "b") ] input |> Map.ofList // evaluates to map [(1, "a"); (2, "b")]
Microsoft.FSharp.Core.StringModuleFunctional programming operators for string processing. Further string operations are available via the member functions on strings and other functionality in System.String and System.Text.RegularExpressions types. Strings and Text
concat: string -> string seq -> stringReturns a new string made by concatenating the given strings with separator sep, that is a1 + sep + ... + sep + aN. The separator string to be inserted between the strings of the input sequence. The sequence of strings to be concatenated. A new string consisting of the concatenated strings separated by the separation string. Thrown when strings is null. let input1 = ["Stefan"; "says:"; "Hello"; "there!"] input1 |> String.concat " " // evaluates "Stefan says: Hello there!" let input2 = [0..9] |> List.map string input2 |> String.concat "" // evaluates "0123456789" input2 |> String.concat ", " // evaluates "0, 1, 2, 3, 4, 5, 6, 7, 8, 9" let input3 = ["No comma"] input3 |> String.concat "," // evaluates "No comma"
keys: Map<'Key,'T> -> System.Collections.Generic.ICollection<'Key>The keys in the map. The sequence will be ordered by the keys of the map. This is an O(n) operation, where n is the number of bindings in the map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.keys // evaluates to seq [1; 2]
tryFind: 'Key -> Map<'Key,'T> -> 'T optionLookup an element in the map, returning a Some value if the element is in the domain of the map and None if not. The input key. The input map. The found Some value or None. Maps are represented as binary trees so this is an O(log n) operation, where n is the number of bindings in the map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.tryFind 1 // evaluates to Some "a" sample |> Map.tryFind 3 // evaluates to None
SomeThe representation of "Value of type 'T" The input value. An option representing the value.
pear: ItemNoneThe representation of "No value"
Sequence expressions work, lazily, with yield!, loops, use and try ... finally. So do list and
array comprehensions, and ranges of any number type and of char:
type Resource(name: string) =
interface System.IDisposable with
member _.Dispose() = printfn "dispose %s" name
let rec countdown n = seq {
if n > 0 then
yield n
yield! countdown (n - 1) }
let numbers = seq {
yield 1
yield! [ 2; 3 ]
for i in 4 .. 5 do
yield i
let mutable i = 6
while i <= 7 do
yield i
i <- i + 1
use r = new Resource("r")
try
yield 8
finally
printfn "finally" }
Zero_450-how-to_022-write-fsharp.md_page.Resourcename: stringstringAn abbreviation for the CLI type . Basic Types
SystemSystem.IDisposableProvides a mechanism for releasing unmanaged resources.
_: ResourceDispose: Resource -> unit -> unitprintfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
countdown: int -> int seqn: intseq: 'T seq -> 'T seqBuilds a sequence using sequence expression syntax The input sequence. The result sequence. seq { for i in 0..10 do yield (i, i*i) }
(>): 'T -> 'T -> boolStructural greater-than The first parameter. The second parameter. The result of the comparison. 5 > 1 // Evaluates to true 5 > 5 // Evaluates to false (1, "a") > (1, "z") // Evaluates to false
(-): ^T1 -> ^T2 -> ^T3Overloaded subtraction operator The first parameter. The second parameter. The result of the operation. 10 - 2 // Evaluates to 8
numbers: int seqi: int(..): ^T -> ^T -> ^T seqThe standard overloaded range operator, e.g. [n..m] for lists, seq {n..m} for sequences The start value of the range. The end value of the range. The sequence spanning the range. [1..4] // Evaluates to [1; 2; 3; 4] [1.5..4.4] // Evaluates to [1.5; 2.5; 3.5] ['a'..'d'] // Evaluates to ['a'; 'b'; 'c'; 'd'] [|1..4|] // Evaluates to an array [|1; 2; 3; 4|] { 1..4 } // Evaluates to a sequence [1; 2; 3; 4])
(<=): 'T -> 'T -> boolStructural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true
(+): ^T1 -> ^T2 -> ^T3Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "World" // Evaluates to "Hello World"
r: ResourceWrite computation expressions
Builders you write work as in .NET: let!, and!, return, yield, for, while, use,
try ... finally and custom operations become calls to your builder's methods, with no reflection:
type OptionBuilder() =
member _.Bind(x, f) = match x with Some v -> f v | None -> None
member _.Return v = Some v
member _.ReturnFrom(o: 'T option) = o
member _.Zero() = Some()
let option = OptionBuilder()
let digit (c: char) =
if c >= '0' && c <= '9' then Some(int c - int '0') else None
let addDigits a b = option {
let! x = digit a
let! y = digit b
return x + y }
Zero_450-how-to_022-write-fsharp.md_page.OptionBuilder_: OptionBuilderBind: OptionBuilder -> 'b option * ('b -> 'c option) -> 'c optionx: 'b optionf: 'b -> 'c optionSomeThe representation of "Value of type 'T" The input value. An option representing the value.
v: 'bNoneThe representation of "No value"
Return: OptionBuilder -> 'a -> 'a optionv: 'aReturnFrom: OptionBuilder -> 'T option -> 'T optiono: 'T optionToptionThe type of optional values. When used from other CLI languages the empty option is the null value. Use the constructors Some and None to create values of this type. Use the values in the Option module to manipulate values of this type, or pattern match against the values directly. 'None' values will appear as the value null to other CLI languages. Instance methods on this type will appear as static methods to other CLI languages due to the use of null as a value representation. Options
Zero: OptionBuilder -> unit -> unit optionoption: OptionBuilder``.ctor``: unit -> OptionBuilderdigit: char -> int optionc: charcharAn abbreviation for the CLI type . Basic Types
(>=): 'T -> 'T -> boolStructural greater-than-or-equal The first parameter. The second parameter. The result of the comparison. 5 >= 1 // Evaluates to true 5 >= 5 // Evaluates to true [1; 5] >= [1; 6] // Evaluates to false
(&&): bool -> bool -> boolBinary 'and'. When used as a binary operator the right hand value is evaluated only on demand The first value. The second value. The result of the operation.
(<=): 'T -> 'T -> boolStructural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true
int: ^T -> intConverts the argument to signed 32-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Int32.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int int 'A' // evaluates to 65 int 0xff // evaluates to 255 int -10 // evaluates to -10
(-): ^T1 -> ^T2 -> ^T3Overloaded subtraction operator The first parameter. The second parameter. The result of the operation. 10 - 2 // Evaluates to 8
addDigits: char -> char -> int optiona: charb: charx: inty: int(+): ^T1 -> ^T2 -> ^T3Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "World" // Evaluates to "Hello World"
addDigits '3' '4' is Some 7 and addDigits '3' 'x' is None. Each let! passes the rest of the
expression to Bind as a closure, an object like any other: in a loop that runs for long, open an
object scope around it (Free F# values with a scope).
async and task aren't there: they need a scheduler and threads zero mode doesn't have.
Delay a value with lazy
lazy makes a value the first time it's read, then keeps it. Force() and .Value read it, and
IsValueCreated says whether it's made yet:
let mutable made = 0
let expensive = lazy (
made <- made + 1
printfn "computing"
6 * 7)
let useExpensive () =
printfn "created: %b" expensive.IsValueCreated
printfn "value: %d" (expensive.Force())
printfn "again: %d, made %d time(s)" expensive.Value made
printfn "created: %b" expensive.IsValueCreated
made: intexpensive: Lazy<int>(+): ^T1 -> ^T2 -> ^T3Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "World" // Evaluates to "Hello World"
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
(*): ^T1 -> ^T2 -> ^T3Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48
useExpensive: unit -> unitIsValueCreated: boolGets a value that indicates whether a value has been created for this instance. if a value has been created for this instance; otherwise, .
Force: unit -> 'TForces the execution of this value and return its result. Same as Value. Mutual exclusion is used to prevent other threads also computing the value. The value of the Lazy object.
Value: intGets the lazily initialized value of the current instance. The instance is initialized to use the parameterless constructor of the type that is being lazily initialized, and permissions to access the constructor are missing. The instance is initialized to use the parameterless constructor of the type that is being lazily initialized, and that type does not have a public, parameterless constructor. The initialization function tries to access on this instance. The lazily initialized value of the current instance.
As in .NET, it's safe to read from several threads (Parallel.For): the first runs the expression,
and the others wait for its value. Reading a lazy value from inside its own expression ends the
program, where .NET would throw. C# programs have the same Lazy<T>.
Count money with decimal
decimal works as in .NET, with the same results: 28 digits after the point, rounding half to even,
and the scale it keeps (19.99M * 3M is 59.97, and 1.0M = 1.00M). %M prints one, %.2f
rounds it:
let price = 19.99M
let total = price * 3M
printfn "%M %.2f %s" total total (string (total / 7M))
printfn "%M %M %M" (1M / 3M) (2M / 3M) (10M / 4M)
printfn "%M %M" (round 2.5M) (round 3.5M)
let amounts = [ 0.1M; 0.2M; 0.3M ]
printfn "%M %b" (List.sum amounts) (List.sum amounts = 0.6M)
printfn "%M" (List.average [ 1M; 2M; 4M ])
price: decimaltotal: decimal(*): ^T1 -> ^T2 -> ^T3Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
string: 'T -> stringConverts the argument to a string using ToString. For standard integer and floating point values and any type that implements IFormattable, ToString conversion uses CultureInfo.InvariantCulture. The input value. The converted string. string 'A' // evaluates to "A" string 0xff // evaluates to "255" string -10 // evaluates to "-10"
(/): ^T1 -> ^T2 -> ^T3Overloaded division operator The first parameter. The second parameter. The result of the operation. 16 / 2 // Evaluates to 8
round: ^T -> ^TRound the given number The input value. The nearest integer to the input value. round 3.49 // Evaluates to 3.0 round -3.49 // Evaluates to -3.0 round 3.5 // Evaluates to 4.0 round -3.5 // Evaluates to -4.0
amounts: decimal listMicrosoft.FSharp.Collections.ListModuleContains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide.
sum: ^T list -> ^TReturns the sum of the elements in the list. The input list. The resulting sum. let input = [ 1; 5; 3; 2 ] input |> List.sum Evaluates to 11. This is an O(n) operation, where n is the length of the list.
(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
average: ^T list -> ^TReturns the average of the values in a non-empty list. The input list. Thrown when the input list is empty. The resulting average. [1.0 .. 9.0] |> List.average Evaluates to 5.0 This is an O(n) operation, where n is the length of the list.
C# zero programs get the same decimal.
Watch the memory
There's no garbage collector: memory a program allocates is never given back. F# allocates more
than you might think. Each list cell, closure, tuple, option, seq enumerator and Map update is an
object, and so is every string sprintf and + make. A program that runs and ends, as a command-line
tool does, can usually ignore this. One that loops for a long time, a game or a server, needs to give
its memory a lifetime. F# gets the same three ways as C#, which
Memory explains in full; this section shows each from F#. [<Struct>]
records, unions and tuples aren't objects, so they need none of it.
An arena holds memory for one lifetime and frees it all at once. Lib's List, Dict and
StrBuilder live in the arena you give them:
// One arena per lifetime: this one holds a list for as long as it lives.
let level = Arena.Create(1024un, "level")
let scores = List<int>.Create(level)
for s in [ 30; 10; 20 ] do
scores.Add s |> ignore
printfn "%d scores, first %d" scores.Count (scores.Get 0)Free F# values with a scope
Ordinary F# code, with its lists, closures and options, allocates with new. Inside
OpenObjectScope those objects go into the arena instead, and leaving the use block frees them.
A loop that would leak on every round then leaks nothing:
// Each round's lists, closures and options go into the frame arena, and
// closing the scope frees them: a thousand rounds leave nothing behind.
let frame = Arena.Create(4096un, "frame")
[<Safety "a round returns an int, and keeps nothing it made">]
let round (n: int) =
use _ = frame.OpenObjectScope()
let evens =
[ 1 .. 100 ]
|> List.map (fun x -> x * 2)
|> List.filter (fun x -> x % 3 <> 0)
let rotated =
match evens with
| [] -> []
| first :: rest -> rest @ [ first ]
let zero = Some n |> Option.map (fun r -> r - n) |> Option.defaultValue 0
List.sum rotated + zero
let first = round 0
let before = GC.GetTotalAllocatedBytes()
let mutable total = 0
for n in 1 .. 1000 do
total <- total + round n
let neverFreed = GC.GetTotalAllocatedBytes() - before
printfn "total %d, first %d, never freed: %d bytes" total first neverFreedThat prints never freed: 0 bytes. Nothing may keep a reference to a value made inside the scope
once it closes: not a module-level value, not a ref cell or a collection from outside. Here round
returns an int, which is copied out. What the compiler keeps for you is safe, unlike in C#: fsc
keeps each lambda that captures nothing, and each union case without fields such as [], in a
static field set by a static constructor, and static constructors allocate outside every scope. A
lambda that captures something is a new object each time, in the arena, and nothing outside points at
it. Set Arena.DebugChecks <- true while testing: closing a scope then stops the program if a static
field points into the arena.
OpenObjectScope is one of the members C# marks unsafe: the compiler can't check that rule, so
a C# caller has to wrap the call in an unsafe block. F# has no such block, and round carries a
[<Safety "...">] attribute instead. The next section is about that.
Say why an unsafe call is safe
When an F# function calls a member C# marks unsafe, such as an arena's Reset, Restore,
Destroy, OpenScope and OpenObjectScope, or an unsafe method of a C# zero library of yours,
the build warns:
Program.fs(63,19): warning ZERO007: Program.unmarked calls Arena.Reset, which is unsafe: ...
Read the member's safety rules (the Arena reference has them), then mark
the function with [<Safety "...">] and the reason this use is correct. It is the
SAFETY comment C# code here writes on an unsafe
block, made part of the code:
// OpenObjectScope is unsafe: nothing made inside it may be used after it.
// [<Safety>] says why this use is correct, as a SAFETY comment does in C#.
[<Safety "the round's values are summed into an int; nothing else is kept">]
let round (n: int) =
use _ = frame.OpenObjectScope()
[ 1 .. n ] |> List.map (fun x -> x * 2) |> List.sumA function that can't promise that by itself passes the duty on with [<RequiresUnsafe>]. It is
then unsafe to call, as an unsafe method is in C#, and the build warns about its callers instead:
// [<RequiresUnsafe>] passes the duty on instead: the function is unsafe to
// call, as an `unsafe` method is in C#, and its callers are the ones to mark.
[<RequiresUnsafe>]
let endFrame () = frame.Reset()
[<Safety "nothing from the frame is in use between frames">]
let playFrame (n: int) =
let total = round n
endFrame ()
totalHow the marks work:
- A mark covers the whole function, with the lambdas and inner functions in it. It goes on a
function, a member or a property, not on a type or a module. On a top-level
do, it covers the file's top-level code. - The reason is required.
[<Safety "">]isn't a mark. - A marked function is never copied into its callers. The F# compiler does that with small
functions, which would put the unsafe call in a function nobody marked.
Safetyis F#'sNoCompilerInliningattribute with a reason, so it can't go on aninlinefunction (FS3151). A small function with[<RequiresUnsafe>]may be copied, and the warning for its caller then names the member it calls. - It's a warning, and it stays. The program builds and runs. The warning is shown in every build
until the function is marked;
<WarningsAsErrors>ZERO007</WarningsAsErrors>in the project makes it an error, and<NoWarn>$(NoWarn);ZERO007</NoWarn>turns it off.
As in C#, the mark is a claim: the build checks that it's there, not that it's true. Catch arena mistakes shows what catches a wrong one when the program runs.
Temporary memory F# checks
Arena.Scratch runs a callback with a scope to allocate from, and frees what it allocated when the
callback returns. What the callback works on goes in as an input, passed by value:
// Temporary memory F# checks: nothing from the scope can leave the callback.
// The callback is made once, as a C# static lambda is, so a call allocates
// nothing. What it works on goes in as the input, by value: here a span.
let medianOf =
ScratchFuncIn<ReadOnlySpan<int>, int>(fun scratch input ->
// A copy to sort, so the caller's items keep their order.
let copy = scratch.AllocSpan<int>(input.Length)
input.CopyTo(copy)
copy.Sort()
copy[copy.Length / 2])
let median (values: ReadOnlySpan<int>) = Arena.Scratch(values, medianOf)
let values = [| 5; 3; 8; 1; 9 |]
// One call first: it sets up what the later calls reuse.
let firstMedian = median (ReadOnlySpan<int>(values))
let scratchBefore = GC.GetTotalAllocatedBytes()
let mutable medians = 0
for _ in 1 .. 1000 do
medians <- medians + median (ReadOnlySpan<int>(values))
let scratchNeverFreed = GC.GetTotalAllocatedBytes() - scratchBefore
printfn "median %d, first still %d, never freed: %d bytes"
(medians / 1000 + firstMedian - 5) values[0] scratchNeverFreedThat prints never freed: 0 bytes after its thousand calls. The scope's spans, lists and text are
ref structs, and F#'s rules for them keep everything inside the callback: a closure can't capture
them, a field, a ref cell or a module-level value can't hold them, and the result can't be one.
sdk/test/fixtures/fs-must-not-compile/ holds one program per way out, and the SDK's tests check
that the build refuses each.
Make the callback once. medianOf is a module-level value, so its delegate is created when the
program starts, as a C# static lambda's is on its first call. A lambda written at the call also
works, and F# picks the delegate type itself, but each call then makes a new delegate that is never
freed:
// A lambda written at the call is a new delegate each time: 48 bytes that
// are never freed, and more if it captures something. Fine for a call or
// two; in a loop, make the callback once, or free them with an object scope.
let inlineBefore = GC.GetTotalAllocatedBytes()
let mutable lengths = 0
for _ in 1 .. 100 do
let length = Arena.Scratch(fun scratch -> scratch.AllocSpan<int>(8).Length)
lengths <- lengths + length
let inlineNeverFreed = GC.GetTotalAllocatedBytes() - inlineBefore
printfn "inline: %d, something never freed: %b" lengths (inlineNeverFreed > 0L)The input is a copy, so a span passed that way still points at your items, and the callback can fill them:
// A span of yours that the callback fills: it gets a copy of the span,
// which points at the same items.
let squaresInto =
ScratchActionIn<Span<int>>(fun scratch output ->
let work = scratch.List<int>()
for i in 1 .. output.Length do
work.Add(i * i)
work.AsSpan().CopyTo(output))
let squares: int[] = Array.zeroCreate 4
Arena.Scratch(Span<int>(squares), squaresInto)
printfn "squares %d %d %d %d" squares[0] squares[1] squares[2] squares[3]Several results come back through a state passed by reference, with &. That form needs the
delegate type written out:
// Several results come back through a state passed by reference. It can't
// be a ref struct (ZERO006), so what goes in with it is an array.
[<Struct>]
type Stats =
{ Values: int[]
mutable Sum: int
mutable Largest: int }
let statsOf =
ScratchAction<Stats>(fun scratch st ->
let sorted = scratch.AllocSpan<int>(st.Values.Length)
Span<int>(st.Values).CopyTo(sorted)
sorted.Sort()
for v in sorted do
st.Sum <- st.Sum + v
st.Largest <- sorted[sorted.Length - 1])
let mutable stats = { Values = values; Sum = 0; Largest = 0 }
Arena.Scratch(&stats, statsOf)
printfn "sum %d, largest %d" stats.Sum stats.LargestHere is the one difference from C#. C# lets that state be a ref struct holding spans of yours, and
its scoped keyword stops the callback from storing scratch memory in it. F# ignores scoped, so the
build checks instead: a callback whose by-reference state is a ref struct (a Span, or a type
with [<IsByRefLike>]) is an error, ZERO006, that names the callback. Pass a ref struct by value,
as above, where a copy can't carry anything out; a state passed by reference is a struct or a record
of ordinary values.
Lists and text that grow come from the scope too. Text takes strings, chars and numbers; a string to keep is copied out into an arena of yours:
// Lists and text that grow, from the scope; the string to keep is copied
// out into an arena of yours.
let reportOf =
ScratchFunc<Arena, string>(fun scratch target ->
let evens = scratch.List<int>(4)
for i in 18 .. -2 .. 0 do
evens.Add i
evens.AsSpan().Sort()
let text = scratch.Text()
text.Append(evens.Count)
text.Append(" evens:")
for e in evens do
text.Append(' ')
text.Append(e)
text.Append(", half of them ")
text.Append(float evens.Count / 2.0)
text.ToArenaString(target))
let mutable keep = Arena.Create(1024un, "keep")
printfn "%s" (Arena.Scratch(&keep, reportOf))C#'s text.Append($"..."), which formats straight into the text, has no F# counterpart: append the
pieces, as here. sprintf works, but makes a string of its own first.
Build for the Commodore 64
An F# project builds for the C64 as a C# one does, with -p:ZeroTarget=c64
(Build for the Commodore 64). samples/Paddles.fs is the paddle-and-ball game
from that guide, in F#: 38 KB, 2 KB more than the C# one. Its test match ends the same way, to the
frame, and allocates nothing while it plays. Struct unions do what C# has to write out by hand:
// Who moves a paddle, and how fast.
[<Struct>]
type Controller =
| Human of humanSpeed: int
| Computer of computerSpeed: int
// What a frame of play led to. A struct union keeps its case and fields in
// the value itself, so the 50 outcomes a second are never allocated (zero
// mode never frees memory). C# had to write this one out by hand.
[<Struct>]
type Outcome =
| InPlay
| HitWall
| HitPaddle of paddle: Side
| Scored of by: SideActive patterns say where the ball is. Marked [<return: Struct>], a partial active pattern returns
a voption instead of an option, an object, so a match on it allocates nothing:
let step left right (m: Match) =
m.LeftTop <- move m.LeftTop left Left m
m.RightTop <- move m.RightTop right Right m
m.Ball <- { m.Ball with X = m.Ball.X + m.Ball.Dx; Y = m.Ball.Y + m.Ball.Dy }
let wall =
match m.Ball with
| OffWall ->
let ball = m.Ball
m.Ball <- { ball with Y = Court.clampBall ball.Y; Dy = -ball.Dy }
HitWall
| _ -> InPlay
let hit =
match m with
| AtPaddle Left -> bounce Left m
| AtPaddle Right -> bounce Right m
| _ -> wall
match m.Ball with
| PointFor side -> Scored side
| _ -> hitThe C64 has about 50 KB for a program and its memory, and some F# costs more there than it looks:
- A lambda passed to a library function, such as
String.iteri (fun i c -> ...), is a closure class. On the title screen alone that came to 2 KB; aforloop costs nothing extra. stringand+on numbers, andprintf, bring in number formatting. The game writes its report withOut.Write, piece by piece.- A function defined inside another one that uses its values is a closure, made when the outer one runs. The game's frame loop is a function of its own, so that playing allocates nothing.
Use libraries
An F# program can reference zero libraries written in C# or F#, with a <ProjectReference> or a
package, as in Create a library:
// An F# program using a C# zero library and an F# one.
module Program
[<EntryPoint>]
let main _ =
let stack = CsLib.IntStack(4)
stack.Push 20
stack.Push 22
Out.Line("C# library: ", int64 (stack.Pop() + stack.Pop()))
let tree = FsLib.Tree.ofList [ 5; 3; 8; 1 ]
Out.Line("F# library: ", int64 (FsLib.Tree.sum tree))
Out.Line(if FsLib.Tree.contains 8 tree then "found 8" else "no 8")
0Ordinary NuGet packages are a different matter: they're built against .NET's runtime, which a zero program doesn't have, and restore refuses them (NU1202), as for C#.
Build a native library
An F# library with <NativeLib>Shared</NativeLib> builds a native library, as a C# one does
(Build a native library). Mark each function to export with
[<UnmanagedCallersOnly>] and an EntryPoint. It must be public and in a module:
[<UnmanagedCallersOnly(EntryPoint = "nl_add")>]
let add (a: int) (b: int) = a + b
[<UnmanagedCallersOnly(EntryPoint = "nl_mul_long")>]
let mulLong (a: int64) (b: int64) = a * b
[<UnmanagedCallersOnly(EntryPoint = "nl_scale")>]
let scale (x: float) (f: float) = x * f
[<UnmanagedCallersOnly(EntryPoint = "nl_sum")>]
let sum (values: nativeptr<int>) (count: int) : int64 =
let mutable total = 0L
for i in 0 .. count - 1 do
total <- total + int64 (NativePtr.get values i)
totalThe same types cross the boundary as in C#: numbers, pointers (nativeptr<'T>), and structs of
those, which in F# are [<Struct>] types with val mutable fields:
[<Struct>]
type Point =
val mutable X: int
val mutable Y: int
Microsoft.FSharp.Core.StructAttributeAdding this attribute to a type causes it to be represented using a CLI struct. Attributes
Zero_450-how-to_022-write-fsharp.md_page.PointX: intintAn abbreviation for the CLI type . Basic Types
Y: intbool and char don't cross, and a function the build can't export (a private one, a generic one,
one with a bool) is an error, ZERO005, that names it.
What's missing
%A, as above, and anything else that needs reflection.asyncandtask. Computation expressions with your own builders work.asin,acos,atan,sinh,coshandtanh. The other math functions are there.- Catching exceptions.
try ... withcompiles, but a raised exception ends the program with its message, asthrowdoes in C# zero mode (Limits).try ... finallyandusework. dict,HashSetand .NET's collections. UseMapandSet, or the library'sDictandList(Choose a collection).- Casting an array to another array type, such as
string[]toobj[], ends the program.