-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathtype-validation.fsx
223 lines (173 loc) · 6.9 KB
/
type-validation.fsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
(*** hide ***)
// This block of code is omitted in the generated HTML documentation. Use
// it to define helpers that you do not want to show in the documentation.
#r @"../../src/FSharpPlus/bin/Release/net8.0/FSharpPlus.dll"
(**
Validation<'Error, 'T>
======================
This is similar to Result<'T, 'Error> but with accumulative errors semantics, instead of short-circuit.
Examples
--------
*)
(**
```f#
#r @"nuget: FSharpPlus"
```
*)
open System
open FSharpPlus
open FSharpPlus.Data
module MovieValidations =
type VError =
| MustNotBeEmpty
| MustBeAtLessThanChars of int
| MustBeADate
| MustBeOlderThan of int
| MustBeWithingRange of decimal * decimal
module String =
let nonEmpty (x:string) : Validation<VError list, string> =
if String.IsNullOrEmpty x
then Failure [MustNotBeEmpty]
else Success x
let mustBeLessThan (i: int) (x: string) : Validation<VError list, string> =
if isNull x || x.Length > i
then Failure [MustBeAtLessThanChars i]
else Success x
module Number =
let mustBeWithin (from, to') x =
if from<= x && x <= to'
then Success x
else Failure [MustBeWithingRange (from, to')]
module DateTime =
let classicMovie year (d: DateTime) =
if d.Year < year
then Success d
else Failure [MustBeOlderThan year]
let date (d: DateTime) =
if d.Date = d
then Success d
else Failure [MustBeADate]
type Genre =
| Classic
| PostClassic
| Modern
| PostModern
| Contemporary
type Movie = {
Id: int
Title: String
ReleaseDate: DateTime
Description: String
Price: decimal
Genre: Genre
} with
static member Create (id, title, releaseDate, description, price, genre) : Validation<VError list, Movie> =
fun title releaseDate description price -> { Id = id; Title = title; ReleaseDate = releaseDate; Description = description; Price = price; Genre = genre }
<!> String.nonEmpty title <* String.mustBeLessThan 100 title
<*> DateTime.classicMovie 1960 releaseDate <* DateTime.date releaseDate
<*> String.nonEmpty description <* String.mustBeLessThan 1000 description
<*> Number.mustBeWithin (0.0m, 999.99m) price
let newRelease = Movie.Create (1, "Midsommar", DateTime (2019, 6, 24), "Midsommar is a 2019 folk horror film written...", 1m, Classic) //Failure [MustBeOlderThan 1960]
let oldie = Movie.Create (2, "Modern Times", DateTime (1936, 2, 5), "Modern Times is a 1936 American comedy film...", 1m, Classic) // Success..
let titleToLong = Movie.Create (3, String.Concat (seq { 1..110 }), DateTime (1950, 1, 1), "11", 1m, Classic) //Failure [MustBeAtLessThanChars 100]
module Person =
type Name = { unName: String }
with static member create s = {unName = s }
type Email = { unEmail: String }
with static member create s = { unEmail = s }
type Age = { unAge : int }
with static member create i = { unAge = i }
type Person = {
name: Name
email: Email
age: Age }
with static member create name email age = { name = name; email = email; age = age }
type Error =
| NameBetween1And50
| EmailMustContainAtChar
| AgeBetween0and120
// Smart constructors
let mkName s =
let l = length s
if (l >= 1 && l <= 50)
then Success <| Name.create s
else Failure [NameBetween1And50]
let mkEmail s =
if String.contains '@' s
then Success <| Email.create s
else Failure [EmailMustContainAtChar]
let mkAge a =
if (a >= 0 && a <= 120)
then Success <| Age.create a
else Failure [AgeBetween0and120]
let mkPerson pName pEmail pAge =
Person.create
<!> mkName pName
<*> mkEmail pEmail
<*> mkAge pAge
// Examples
let validPerson = mkPerson "Bob" "bob@gmail.com" 25
// Success ({name = {unName = "Bob"}; email = {unEmail = "bob@gmail.com"}; age = {unAge = 25}})
let badName = mkPerson "" "bob@gmail.com" 25
// Failure [NameBetween1And50]
let badEmail = mkPerson "Bob" "bademail" 25
// Failure [EmailMustContainAtChar]
let badAge = mkPerson "Bob" "bob@gmail.com" 150
// Failure [AgeBetween0and120]
let badEverything = mkPerson "" "bademail" 150
// Failure [NameBetween1And50;EmailMustContainAtChar;AgeBetween0and120]
open FSharpPlus.Lens
let asMaybeGood = validPerson ^? Validation._Success
// Some ({name = {unName = "Bob"}; email = {unEmail = "bob@gmail.com"}; age = {unAge = 25}})
let asMaybeBad = badEverything ^? Validation._Success
// None
let asResultGood = validPerson ^. Validation.isoValidationResult
// Ok ({name = {unName = "Bob"}; email = {unEmail = "bob@gmail.com"}; age = {unAge = 25}})
let asResultBad = badEverything ^. Validation.isoValidationResult
// Error [NameBetween1And50;EmailMustContainAtChar;AgeBetween0and120]
module Email =
// ***** Types *****
type AtString = AtString of string
type PeriodString = PeriodString of string
type NonEmptyString = NonEmptyString of string
type Email = Email of string
type VError =
| MustNotBeEmpty
| MustContainAt
| MustContainPeriod
// ***** Base smart constructors *****
// String must contain an '@' character
let atString (x: string) : Validation<VError list, AtString> =
if String.contains '@' x then Success <| AtString x
else Failure [MustContainAt]
// String must contain an '.' character
let periodString (x: string) : Validation<VError list, PeriodString> =
if String.contains '.' x
then Success <| PeriodString x
else Failure [MustContainPeriod]
// String must not be empty
let nonEmptyString (x: string) : Validation<VError list, NonEmptyString> =
if not <| String.IsNullOrEmpty x
then Success <| NonEmptyString x
else Failure [MustNotBeEmpty]
// ***** Combining smart constructors *****
let email (x: string) : Validation<VError list, Email> =
result (Email x) <*
nonEmptyString x <*
atString x <*
periodString x
// ***** Example usage *****
let success = email "bob@gmail.com"
// Success (Email "bob@gmail.com")
let failureAt = email "bobgmail.com"
// Failure [MustContainAt]
let failurePeriod = email "bob@gmailcom"
// Failure [MustContainPeriod]
let failureAll = email ""
// Failure [MustNotBeEmpty;MustContainAt;MustContainPeriod]
(**
Recommended reading
-------------------
- Highly recommended Matt Thornton's blog [Grokking Applicative Validation](https://dev.to/choc13/grokking-applicative-validation-lh6).
It contains examples using F#+ and an explanation from scratch.
*)