|
| 1 | +--- |
| 2 | +order: 17 |
| 3 | +title: ComputationExpressions.fs |
| 4 | +excerpt_separator: <!--more--> |
| 5 | +code: | |
| 6 | + // Sequence generation |
| 7 | + let rec fizzBuzzSeq n = |
| 8 | + seq { |
| 9 | + yield |
| 10 | + match n with |
| 11 | + | x when x % 15 = 0 -> "fizzbuzz" |
| 12 | + | x when x % 3 = 0 -> "fizz" |
| 13 | + | x when x % 5 = 0 -> "buzz" |
| 14 | + | _ -> n.ToString() |
| 15 | +
|
| 16 | + yield! fizzBuzzSeq (n + 1) |
| 17 | + } |
| 18 | +
|
| 19 | + fizzBuzzSeq 1 |> Seq.take 100 |> Seq.iter (printfn "%s") |
| 20 | +
|
| 21 | + // Asynchronous programming with computation expressions |
| 22 | + let fetchDataAsync url = async { |
| 23 | + printfn "Fetching data from %s..." url |
| 24 | + do! Async.Sleep 1000 // Simulate network delay |
| 25 | + return sprintf "Data from %s" url |
| 26 | + } |
| 27 | +
|
| 28 | + // Custom computation expression for validation |
| 29 | + type ValidationBuilder() = |
| 30 | + member _.Bind(x, f) = |
| 31 | + match x with |
| 32 | + | Ok value -> f value |
| 33 | + | Error e -> Error e |
| 34 | + member _.Return(x) = Ok x |
| 35 | + member _.ReturnFrom(x) = x |
| 36 | +
|
| 37 | + let validate = ValidationBuilder() |
| 38 | +
|
| 39 | + type Person = { Name: string; Age: int } |
| 40 | +
|
| 41 | + // Using our custom computation expression |
| 42 | + let validatePerson age name = validate { |
| 43 | + let! validAge = |
| 44 | + if age >= 0 && age < 150 then Ok age |
| 45 | + else Error "Age must be between 0 and 150" |
| 46 | + |
| 47 | + let! validName = |
| 48 | + if String.length name > 0 then Ok name |
| 49 | + else Error "Name cannot be empty" |
| 50 | + |
| 51 | + return { Name = validName; Age = validAge } |
| 52 | + } |
| 53 | +
|
| 54 | + // Using multiple computation expressions together |
| 55 | + let processPersonAsync person = async { |
| 56 | + let result = validatePerson person.Age person.Name |
| 57 | + match result with |
| 58 | + | Ok validated -> |
| 59 | + return! fetchDataAsync $"profile/{validated.Name}" |
| 60 | + | Error msg -> |
| 61 | + return $"Validation error: {msg}" |
| 62 | + } |
| 63 | +
|
| 64 | + processPersonAsync { Name = "Snowdrop"; Age = 13} |
| 65 | + |> Async.RunSynchronously |
| 66 | +--- |
| 67 | +## Expressive Control Flow with Computation Expressions |
| 68 | + |
| 69 | +F# computation expressions provide an elegant syntax for complex control flows with a clean, readable notation that some say is F#'s superpower. |
| 70 | +<!--more--> |
| 71 | +- **Simplified asynchronous code** makes non-blocking operations read like synchronous code |
| 72 | +- **Custom control flow abstractions** create domain-specific mini-languages |
| 73 | +- **Seamless error handling** with [railway-oriented programming](https://fsharpforfunandprofit.com/rop/) patterns |
| 74 | +- **Elegant data transformations** by hiding boilerplate and focusing on business logic |
| 75 | +- **Composable workflows** that can be combined and nested for complex operations |
| 76 | + |
0 commit comments