diff --git a/_snippets/computation_expressions.md b/_snippets/computation_expressions.md index d5aba953..42a728c2 100644 --- a/_snippets/computation_expressions.md +++ b/_snippets/computation_expressions.md @@ -5,13 +5,12 @@ excerpt_separator: code: | // Define a custom computation expression for validation type ValidationBuilder() = - member _.Bind(x, f) = + member _.Bind(x, f) = // Defines "let!" match x with | Ok value -> f value | Error e -> Error e - member _.Return(x) = Ok x - member _.ReturnFrom(x) = x - + member _.Return(x) = Ok x // Defines "return" + member _.ReturnFrom(x) = x // Defines "return!" let validate = ValidationBuilder() type Person = { Name: string; Age: int } @@ -22,11 +21,14 @@ code: | if age >= 0 && age < 150 then Ok age else Error "Age must be between 0 and 150" - let! validName = + let! nonEmptyName = if String.length name > 0 then Ok name else Error "Name cannot be empty" - return { Name = validName; Age = validAge } + if String.length name > 100 then + return! Error "Name is too long!" + else + return { Name = nonEmptyName; Age = validAge } } --- ## Clean Code with Computation Expressions diff --git a/_snippets/sequence_expressions.md b/_snippets/sequence_expressions.md index e5044a38..90916d95 100644 --- a/_snippets/sequence_expressions.md +++ b/_snippets/sequence_expressions.md @@ -3,15 +3,14 @@ order: 15 title: SequenceExpressions.fs excerpt_separator: code: | - // A function generating a sequence of numbers let rec fizzBuzzSeq n = seq { - yield - match n with - | x when x % 15 = 0 -> "fizzbuzz" - | x when x % 3 = 0 -> "fizz" - | x when x % 5 = 0 -> "buzz" - | _ -> n.ToString() - + match n with + | x when x % 15 = 0 -> "fizzbuzz" + | x when x % 3 = 0 -> "fizz" + | x when x % 5 = 0 -> "buzz" + | _ -> n.ToString() + + // Tail recursion makes this as efficient as a "while" loop yield! fizzBuzzSeq (n + 1) }