F# Patterns
This file extends common/patterns.md with F#-specific content.
This file extends common/patterns.md with F#-specific content.
--- paths:
---
This file extends [common/patterns.md](../common/patterns.md) with F#-specific content.
Use `Result<'T, 'TError>` with railway-oriented programming instead of exceptions for expected failures.
type OrderError =
| InvalidCustomer of string
| EmptyItems
| ItemOutOfStock of sku: string
let validateOrder (request: CreateOrderRequest) : Result<ValidatedOrder, OrderError> =
if String.IsNullOrWhiteSpace request.CustomerId then
Error(InvalidCustomer "CustomerId is required")
elif request.Items |> List.isEmpty then
Error EmptyItems
else
Ok { CustomerId = request.CustomerId; Items = request.Items }Prefer `Option<'T>` over null. Use `Option.map`, `Option.bind`, and `Option.defaultValue` to transform.
let findUser (id: Guid) : User option =
users |> Map.tryFind id
let getUserEmail userId =
findUser userId
|> Option.map (fun u -> u.Email)
|> Option.defaultValue "unknown@example.com"Model business states explicitly. The compiler enforces exhaustive handling.
type PaymentState =
| AwaitingPayment of amount: decimal
| Paid of paidAt: DateTimeOffset * transactionId: string
| Refunded of refundedAt: DateTimeOffset * reason: string
| Failed of error: string
let describePayment = function
| AwaitingPayment amount -> quot;Awaiting payment of {amount:C}"
| Paid (at, txn) -> quot;Paid at {at} (txn: {txn})"
| Refunded (at, reason) -> quot;Refunded at {at}: {reason}"
| Failed error -> quot;Payment failed: {error}"Use computation expressions to simplify sequential operations that may fail.
let placeOrder request =
result {
let! validated = validateOrder request
let! inventory = checkInventory validated.Items
let! order = createOrder validated inventory
return order
}[<RequireQualifiedAccess>]
module Order =
let create customerId items = { Id = Guid.NewGuid(); CustomerId = customerId; Items = items; Status = Pending }
let confirm order = { order with Status = Confirmed(DateTimeOffset.UtcNow) }
let cancel reason order = { order with Status = Cancelled reason }type OrderDeps =
{ FindOrder: Guid -> Task<Order option>
SaveOrder: Order -> Task<unit>
SendNotification: Order -> Task<unit> }
let processOrder (deps: OrderDeps) orderId =
task {
match! deps.FindOrder orderId with
| None -> return Error "Order not found"
| Some order ->
let confirmed = Order.confirm order
do! deps.SaveOrder confirmed
do! deps.SendNotification confirmed
return Ok confirmed
}