File tree Expand file tree Collapse file tree 2 files changed +15
-14
lines changed Expand file tree Collapse file tree 2 files changed +15
-14
lines changed Original file line number Diff line number Diff line change @@ -5,13 +5,12 @@ excerpt_separator: <!--more-->
55code : |
66 // Define a custom computation expression for validation
77 type ValidationBuilder() =
8- member _.Bind(x, f) =
8+ member _.Bind(x, f) = // Defines "let!"
99 match x with
1010 | Ok value -> f value
1111 | Error e -> Error e
12- member _.Return(x) = Ok x
13- member _.ReturnFrom(x) = x
14-
12+ member _.Return(x) = Ok x // Defines "return"
13+ member _.ReturnFrom(x) = x // Defines "return!"
1514 let validate = ValidationBuilder()
1615
1716 type Person = { Name: string; Age: int }
@@ -22,11 +21,14 @@ code: |
2221 if age >= 0 && age < 150 then Ok age
2322 else Error "Age must be between 0 and 150"
2423
25- let! validName =
24+ let! nonEmptyName =
2625 if String.length name > 0 then Ok name
2726 else Error "Name cannot be empty"
2827
29- return { Name = validName; Age = validAge }
28+ if String.length name > 100 then
29+ return! Error "Name is too long!"
30+ else
31+ return { Name = nonEmptyName; Age = validAge }
3032 }
3133---
3234## Clean Code with Computation Expressions
Original file line number Diff line number Diff line change @@ -3,15 +3,14 @@ order: 15
33title : SequenceExpressions.fs
44excerpt_separator : <!--more-->
55code : |
6- // A function generating a sequence of numbers
76 let rec fizzBuzzSeq n = seq {
8- yield
9- match n with
10- | x when x % 15 = 0 -> "fizzbuzz "
11- | x when x % 3 = 0 -> "fizz "
12- | x when x % 5 = 0 -> "buzz"
13- | _ -> n.ToString()
14-
7+ match n with
8+ | x when x % 15 = 0 -> "fizzbuzz"
9+ | x when x % 3 = 0 -> "fizz "
10+ | x when x % 5 = 0 -> "buzz "
11+ | _ -> n.ToString()
12+
13+ // Tail recursion makes this as efficient as a "while" loop
1514 yield! fizzBuzzSeq (n + 1)
1615 }
1716
You can’t perform that action at this time.
0 commit comments