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-->
5
5
code : |
6
6
// Define a custom computation expression for validation
7
7
type ValidationBuilder() =
8
- member _.Bind(x, f) =
8
+ member _.Bind(x, f) = // Defines "let!"
9
9
match x with
10
10
| Ok value -> f value
11
11
| 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!"
15
14
let validate = ValidationBuilder()
16
15
17
16
type Person = { Name: string; Age: int }
@@ -22,11 +21,14 @@ code: |
22
21
if age >= 0 && age < 150 then Ok age
23
22
else Error "Age must be between 0 and 150"
24
23
25
- let! validName =
24
+ let! nonEmptyName =
26
25
if String.length name > 0 then Ok name
27
26
else Error "Name cannot be empty"
28
27
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 }
30
32
}
31
33
---
32
34
## Clean Code with Computation Expressions
Original file line number Diff line number Diff line change @@ -3,15 +3,14 @@ order: 15
3
3
title : SequenceExpressions.fs
4
4
excerpt_separator : <!--more-->
5
5
code : |
6
- // A function generating a sequence of numbers
7
6
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
15
14
yield! fizzBuzzSeq (n + 1)
16
15
}
17
16
You can’t perform that action at this time.
0 commit comments