Repository F# setup
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Layers
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.PlatformService
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScriptService Contracts
A record works because you own both sides: the workflow names AppEnv, and you supply an AppEnv. A package
author cannot do that. Axial.Console is compiled long before your AppEnv exists, so Console.writeLine cannot
mention it.
A package declares an ordinary interface named IHasFoo with a single member Foo:
The examples on this page use these application types:
Show page setup
// Setup for the checked examples on this page.
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Layers
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.PlatformService
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScript
/// Fails the docs test when an example's result differs from the value shown.
let shouldEqual expected actual =
if actual <> expected then failwithf "Expected %A but got %A" expected actual
type Order = { Id: int }
type CheckoutError = AlreadySaved of int
type IOrderRepository =
abstract Save: Order -> Result<unit, CheckoutError>
type IEmailSender =
abstract SendConfirmation: Order -> unittype IHasOrders =
abstract Orders: IOrderRepository
FsLiveDocsGeneratedPage20_2D306DEB1823.IHasOrdersOrders: IHasOrders -> unit -> IOrderRepositoryFsLiveDocsGeneratedPage20_2D306DEB1823.IOrderRepositoryThe helper constrains its environment to that interface instead of naming a type:
[<RequireQualifiedAccess>]
module Orders =
let service<'env, 'error when 'env :> IHasOrders> : Flow<'env, 'error, IOrderRepository> =
Flow.envWith _.Orders
let save order : Flow<#IHasOrders, CheckoutError, unit> =
flow {
let! orders = Orders.service
do! orders.Save order
}
Microsoft.FSharp.Core.RequireQualifiedAccessAttributeThis attribute is used to indicate that references to the elements of a module, record or union type require explicit qualified access. Attributes
FsLiveDocsGeneratedPage20_2D306DEB1823.Ordersservice: Flow<'env,'error,IOrderRepository>enverrorFsLiveDocsGeneratedPage20_2D306DEB1823.IHasOrdersAxial.Flow`3FsLiveDocsGeneratedPage20_2D306DEB1823.IOrderRepositoryAxial.FlowenvWith: ('env -> 'value) -> Flow<'env,'error,'value>Projects one value from the current environment. This is the primary way to access app dependencies, configuration, or request metadata stored in env. The projection runs only when the flow is executed, so constructing the flow is still pure and side-effect free. Prefer small projections over passing a large environment deeper into reusable helpers. A function that extracts a value from the environment. A containing the projected value. let currentTime () = Flow.envWith (fun (environment: BaseRuntime) -> environment.Clock.UtcNow())
_arg1: 'envOrders: IOrderRepositorysave: Order -> Flow<'a,CheckoutError,unit>order: OrderFsLiveDocsGeneratedPage20_2D306DEB1823.CheckoutErrorunitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
flow: FlowBuilderThe universal flow { } computation expression.
orders: IOrderRepositorySave: Order -> Result<unit,CheckoutError>Read Flow<#IHasOrders, …> as "any environment that can give me an IOrderRepository". This is still just
Flow.envWith; the interface only says which member it may read.
Supplying one
Your record implements the contracts it satisfies; its fields can retain their existing names:
type IHasEmail =
abstract Email: IEmailSender
[<RequireQualifiedAccess>]
module Email =
let service<'env, 'error when 'env :> IHasEmail> : Flow<'env, 'error, IEmailSender> =
Flow.envWith _.Email
type AppEnv =
{ Orders: IOrderRepository
Email: IEmailSender }
interface IHasOrders with member this.Orders = this.Orders
interface IHasEmail with member this.Email = this.Email
FsLiveDocsGeneratedPage20_2D306DEB1823.IHasEmailEmail: IHasEmail -> unit -> IEmailSenderFsLiveDocsGeneratedPage20_2D306DEB1823.IEmailSenderMicrosoft.FSharp.Core.RequireQualifiedAccessAttributeThis attribute is used to indicate that references to the elements of a module, record or union type require explicit qualified access. Attributes
FsLiveDocsGeneratedPage20_2D306DEB1823.Emailservice: Flow<'env,'error,IEmailSender>enverrorAxial.Flow`3Axial.FlowenvWith: ('env -> 'value) -> Flow<'env,'error,'value>Projects one value from the current environment. This is the primary way to access app dependencies, configuration, or request metadata stored in env. The projection runs only when the flow is executed, so constructing the flow is still pure and side-effect free. Prefer small projections over passing a large environment deeper into reusable helpers. A function that extracts a value from the environment. A containing the projected value. let currentTime () = Flow.envWith (fun (environment: BaseRuntime) -> environment.Clock.UtcNow())
_arg1: 'envEmail: IEmailSenderFsLiveDocsGeneratedPage20_2D306DEB1823.AppEnvOrders: IOrderRepositoryFsLiveDocsGeneratedPage20_2D306DEB1823.IOrderRepositoryFsLiveDocsGeneratedPage20_2D306DEB1823.IHasOrdersthis: AppEnvOrders: AppEnv -> unit -> IOrderRepositoryEmail: AppEnv -> unit -> IEmailSendermember this.Orders = this.Orders is not recursive. F# interface implementations are always explicit, so the
interface member is not in scope on the record itself and the right-hand side resolves to the field. A record with no
such field fails to compile rather than looping.
Needing more than one
Contracts are distinct interfaces, so a workflow can require several and the constraints merge on their own:
let submit<'env when 'env :> IHasOrders and 'env :> IHasEmail> (order: Order) : Flow<'env, CheckoutError, unit> =
flow {
let! orders = Orders.service
let! email = Email.service
do! orders.Save order
email.SendConfirmation order
}
submit: Order -> Flow<'env,CheckoutError,unit>envFsLiveDocsGeneratedPage20_2D306DEB1823.IHasOrdersFsLiveDocsGeneratedPage20_2D306DEB1823.IHasEmailorder: OrderFsLiveDocsGeneratedPage20_2D306DEB1823.OrderAxial.Flow`3FsLiveDocsGeneratedPage20_2D306DEB1823.CheckoutErrorunitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
flow: FlowBuilderThe universal flow { } computation expression.
orders: IOrderRepositoryFsLiveDocsGeneratedPage20_2D306DEB1823.Ordersservice: Flow<'env,'error,IOrderRepository>email: IEmailSenderFsLiveDocsGeneratedPage20_2D306DEB1823.Emailservice: Flow<'env,'error,IEmailSender>Save: Order -> Result<unit,CheckoutError>SendConfirmation: Order -> unitAppEnv satisfies both constraints, so it runs save and submit alike:
let gate = obj()
let mutable saved = []
let mutable sent = []
let env =
{ Orders =
{ new IOrderRepository with
member _.Save order =
lock gate (fun () ->
if List.contains order.Id saved then
Error(AlreadySaved order.Id)
else
saved <- order.Id :: saved
Ok()) }
Email = { new IEmailSender with member _.SendConfirmation order = lock gate (fun () -> sent <- order.Id :: sent) } }
submit { Id = 1 } |> Flow.run env |> shouldEqual (Exit.Success())
save { Id = 1 } |> Flow.run env |> shouldEqual (Exit.Failure(Cause.Fail(AlreadySaved 1)))
lock gate (fun () -> List.rev sent) |> shouldEqual [ 1 ]
gate: obj``.ctor``: unit -> unitInitializes a new instance of the class.
saved: int listsent: int listenv: AppEnvOrders: IOrderRepositoryFsLiveDocsGeneratedPage20_2D306DEB1823.IOrderRepository_: IOrderRepositorySave: Order -> Result<unit,CheckoutError>order: Orderlock: 'Lock -> (unit -> 'T) -> 'TExecute the function as a mutual-exclusion region using the input value as a lock. The object to be locked. The action to perform during the lock. The resulting value. open System.Linq /// A counter object, supporting unlocked and locked increment type TestCounter () = let mutable count = 0 /// Increment the counter, unlocked member this.IncrementWithoutLock() = count <- count + 1 /// Increment the counter, locked member this.IncrementWithLock() = lock this (fun () -> count <- count + 1) /// Get the count member this.Count = count let counter = TestCounter() // Create a parallel sequence to that uses all our CPUs (seq {1..100000}).AsParallel() .ForAll(fun _ -> counter.IncrementWithoutLock()) // Evaluates to a number between 1-100000, non-deterministically because there is no locking counter.Count let counter2 = TestCounter() // Create a parallel sequence to that uses all our CPUs (seq {1..100000}).AsParallel() .ForAll(fun _ -> counter2.IncrementWithLock()) // Evaluates to 100000 deterministically because the increment to the counter object is locked counter2.Count
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.
contains: 'T -> 'T list -> boolTests if the list contains the specified element. The value to locate in the input list. The input list. True if the input list contains the specified element; false otherwise. [1..9] |> List.contains 0 Evaluates to false. [1..9] |> List.contains 3 Evaluates to true. let input = [1, "SpongeBob"; 2, "Patrick"; 3, "Squidward"; 4, "Mr. Krabs"] input |> List.contains (2, "Patrick") Evaluates to true. let input = [1, "SpongeBob"; 2, "Patrick"; 3, "Squidward"; 4, "Mr. Krabs"] input |> List.contains (22, "Patrick") Evaluates to false. This is an O(n) operation, where n is the length of the list.
Id: intErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
AlreadySaved(::)OkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
Email: IEmailSenderFsLiveDocsGeneratedPage20_2D306DEB1823.IEmailSender_: IEmailSenderSendConfirmation: Order -> unitsubmit: Order -> Flow<'env,CheckoutError,unit>(|>): '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
Axial.Flowrun: 'env -> Flow<'env,'error,'value> -> Exit<'value,'error>Runs the workflow and blocks until the final exit is available. The environment used by the workflow. The workflow to run. The final workflow exit. let exit = workflow |> Flow.run environment
shouldEqual: 'a -> 'a -> unitAxial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
SuccessThe workflow completed successfully.
save: Order -> Flow<'a,CheckoutError,unit>FailureThe workflow failed due to a specific cause.
Axial.Cause`1Represents the cause of a failed workflow. The type of the domain-specific failure value.
FailAn expected domain-specific failure.
rev: 'T list -> 'T listReturns a new list with the elements in reverse order. The input list. The reversed list. let inputs = [ 0; 1; 2 ] inputs |> List.rev Evaluates to [ 2; 1; 0 ]. This is an O(n) operation, where n is the length of the list.
When a combination recurs, name it and a single constraint covers it:
type ICheckoutEnv =
inherit IHasOrders
inherit IHasEmail
let submitOrder (order: Order) : Flow<#ICheckoutEnv, CheckoutError, unit> = submit order
FsLiveDocsGeneratedPage20_2D306DEB1823.ICheckoutEnvFsLiveDocsGeneratedPage20_2D306DEB1823.IHasOrdersFsLiveDocsGeneratedPage20_2D306DEB1823.IHasEmailsubmitOrder: Order -> Flow<'a,CheckoutError,unit>order: OrderFsLiveDocsGeneratedPage20_2D306DEB1823.OrderAxial.Flow`3FsLiveDocsGeneratedPage20_2D306DEB1823.CheckoutErrorunitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
submit: Order -> Flow<'env,CheckoutError,unit>#IHasOrders carries exactly one constraint, which is why the aggregate exists. Each occurrence of #T is a
separate type variable, so when an environment appears more than once in a signature, use the explicit
<'env when 'env :> … and 'env :> …> form. The
troubleshooting types
page shows the exact rule and where it bites.
When to declare one
For application code, use the record described in the environment. It needs no interface.
Declare a contract when you are publishing a helper whose callers you will never see, such as a shared library or a
package like Axial.FileSystem. A record cannot cover that case, because the helper cannot know the caller's record
type.
Writing a package that ships services is covered in providing services from a package.

