├── .gitignore ├── .vscode └── settings.json ├── MySolution ├── MySolution.sln ├── src │ └── MyProject │ │ ├── Company.fs │ │ ├── CompanyCredit.fs │ │ ├── Customer.fs │ │ ├── MyProject.fsproj │ │ ├── Program.fs │ │ └── SharedFunctions.fs └── tests │ └── MyProjectTests │ ├── MyProjectTests.fsproj │ ├── Program.fs │ └── Tests.fs ├── README.md └── init.txt /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "FSharp.inlayHints.enabled": false, 3 | "FSharp.inlayHints.typeAnnotations": false, 4 | "FSharp.inlayHints.parameterNames": false 5 | } -------------------------------------------------------------------------------- /MySolution/MySolution.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{3B091EBE-7009-4F71-AD51-EFF985687841}" 7 | EndProject 8 | Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "MyProject", "src\MyProject\MyProject.fsproj", "{8332BC9F-7E12-4F0A-83C0-5E68BBC9A0B3}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{D593FB90-5893-4339-A060-5156F7D0F868}" 11 | EndProject 12 | Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "MyProjectTests", "tests\MyProjectTests\MyProjectTests.fsproj", "{7B54D377-981F-451C-A997-E6B934CC7A3E}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {8332BC9F-7E12-4F0A-83C0-5E68BBC9A0B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {8332BC9F-7E12-4F0A-83C0-5E68BBC9A0B3}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {8332BC9F-7E12-4F0A-83C0-5E68BBC9A0B3}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {8332BC9F-7E12-4F0A-83C0-5E68BBC9A0B3}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {7B54D377-981F-451C-A997-E6B934CC7A3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {7B54D377-981F-451C-A997-E6B934CC7A3E}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {7B54D377-981F-451C-A997-E6B934CC7A3E}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {7B54D377-981F-451C-A997-E6B934CC7A3E}.Release|Any CPU.Build.0 = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {8332BC9F-7E12-4F0A-83C0-5E68BBC9A0B3} = {3B091EBE-7009-4F71-AD51-EFF985687841} 34 | {7B54D377-981F-451C-A997-E6B934CC7A3E} = {D593FB90-5893-4339-A060-5156F7D0F868} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /MySolution/src/MyProject/Company.fs: -------------------------------------------------------------------------------- 1 | namespace App 2 | 3 | type Classification = Gold | Silver | Bronze 4 | 5 | type Company = { 6 | Id: int 7 | Name: string 8 | Classification: Classification 9 | } 10 | 11 | -------------------------------------------------------------------------------- /MySolution/src/MyProject/CompanyCredit.fs: -------------------------------------------------------------------------------- 1 | namespace App 2 | 3 | type CompanyCredit = 4 | | HasCreditLimit of int 5 | | DoesNotHaveCreditLimit 6 | 7 | [] 8 | module CompanyCredit = 9 | 10 | let private requiresCreditCheck (company:Company) = 11 | match company.Classification with 12 | | Gold -> false 13 | | _ -> true 14 | 15 | let calculateCreditLimit (company:Company) (limit:int) = 16 | match company.Classification with 17 | | Gold -> DoesNotHaveCreditLimit 18 | | Silver -> 2 * limit |> HasCreditLimit 19 | | Bronze -> limit |> HasCreditLimit 20 | 21 | let getCreditLimit (checkCredit:Company -> int) (company:Company) = 22 | if company |> requiresCreditCheck then 23 | company 24 | |> checkCredit 25 | |> calculateCreditLimit company 26 | else DoesNotHaveCreditLimit 27 | -------------------------------------------------------------------------------- /MySolution/src/MyProject/Customer.fs: -------------------------------------------------------------------------------- 1 | namespace App 2 | 3 | open System 4 | open FsToolkit.ErrorHandling 5 | 6 | type CustomerValidationErrors = 7 | | EmptyFirstName of string 8 | | EmptySurname of string 9 | | InvalidEmail of string 10 | | CustomerTooYoung of DateOnly 11 | 12 | type FirstName = private FirstName of string 13 | 14 | [] 15 | module FirstName = 16 | let create (input:string) = 17 | if String.IsNullOrWhiteSpace(input) |> not then Ok (FirstName input) 18 | else Error (EmptyFirstName input) 19 | 20 | let value (input:FirstName) = input |> fun (FirstName firstName) -> firstName 21 | 22 | type Surname = private Surname of string 23 | 24 | [] 25 | module Surname = 26 | let create (input:string) = 27 | if String.IsNullOrWhiteSpace(input) |> not then Ok (Surname input) 28 | else Error (EmptySurname input) 29 | 30 | let value (input:Surname) = input |> fun (Surname surname) -> surname 31 | 32 | type Email = private Email of string 33 | 34 | [] 35 | module Email = 36 | let create (input:string) = 37 | match input with 38 | | IsNullOrWhiteSpace -> Error (InvalidEmail input) 39 | | IsValidEmail _ -> Ok (Email input) 40 | | _ -> Error (InvalidEmail input) 41 | 42 | let value (input:Email) = input |> fun (Email email) -> email 43 | 44 | type DateOfBirth = private DateOfBirth of DateOnly 45 | 46 | [] 47 | module DateOfBirth = 48 | let private getAge (now:DateOnly) (dateOfBirth:DateOnly) = 49 | let age = now.Year - dateOfBirth.Year 50 | if now.Month < dateOfBirth.Month || now.Month = dateOfBirth.Month && now.Day < dateOfBirth.Day then age - 1 51 | else age 52 | 53 | let create (nowProvider:unit -> DateTime) (dateOfBirth:DateOnly) = 54 | let today = nowProvider () |> DateOnly.FromDateTime 55 | if getAge today dateOfBirth >= 21 then Ok (DateOfBirth dateOfBirth) 56 | else Error (CustomerTooYoung dateOfBirth) 57 | 58 | let value (input:DateOfBirth) = input |> fun (DateOfBirth dateOfBirth) -> dateOfBirth 59 | 60 | type Customer = { 61 | FirstName: FirstName 62 | Surname: Surname 63 | Email: Email 64 | DateOfBirth: DateOfBirth 65 | } 66 | 67 | type AddCustomerServices = { 68 | NowProvider: unit -> DateTime 69 | GetCompanyById: int -> Company option 70 | CreateCustomer: Customer * Company * CompanyCredit -> unit 71 | CreditCheckService: Company -> int 72 | } 73 | 74 | type AddCustomerErrors = 75 | | FailedCreateValidation of CustomerValidationErrors list 76 | | CompanyNotFound of int 77 | | CompanyNotSupplied 78 | 79 | [] 80 | module Customer = 81 | let private create firstName surname email dateOfBirth = 82 | { 83 | FirstName = firstName 84 | Surname = surname 85 | Email = email 86 | DateOfBirth = dateOfBirth 87 | } 88 | 89 | let tryCreate (nowProvider:unit -> DateTime) firstName surname email dateOfBirth = 90 | validation { 91 | let! firstName' = firstName |> FirstName.create 92 | and! surname' = surname |> Surname.create 93 | and! email' = email |> Email.create 94 | and! dateOfBirth' = dateOfBirth |> DateOfBirth.create nowProvider 95 | return create firstName' surname' email' dateOfBirth' 96 | } 97 | 98 | [] 99 | module CustomerService = 100 | let addCustomer (services:AddCustomerServices) firstName surname email dateOfBirth companyId = 101 | result { 102 | let! customer = 103 | Customer.tryCreate services.NowProvider firstName surname email dateOfBirth 104 | |> Result.mapError FailedCreateValidation 105 | let! company = 106 | services.GetCompanyById companyId 107 | |> Result.requireSome (CompanyNotFound companyId) 108 | let creditLimit = 109 | company 110 | |> CompanyCredit.getCreditLimit services.CreditCheckService 111 | return services.CreateCustomer (customer, company, creditLimit) 112 | } 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /MySolution/src/MyProject/MyProject.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net7.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /MySolution/src/MyProject/Program.fs: -------------------------------------------------------------------------------- 1 | open System 2 | open App 3 | 4 | let nowProvider = fun () -> DateTime.Now 5 | 6 | let companyRepository id = 7 | Some { Id = id; Name = $"Some Imaginary Company"; Classification = Gold } 8 | 9 | let customerRepository (input:Customer * Company * CompanyCredit) = () 10 | 11 | let creditService customer = 1000 12 | 13 | let services = { 14 | NowProvider = nowProvider 15 | GetCompanyById = companyRepository 16 | CreateCustomer = customerRepository 17 | CreditCheckService = creditService 18 | } 19 | 20 | let firstName = "Geraldine" 21 | let surname = "Grainger-Tuppence" 22 | let email = "geraldine@someimaginarycompany.co.uk" 23 | let dateOfBirth = DateTime(1975, 1, 13) |> DateOnly.FromDateTime 24 | let companyId = 42 25 | 26 | CustomerService.addCustomer services firstName surname email dateOfBirth companyId 27 | |> printfn "%A" 28 | -------------------------------------------------------------------------------- /MySolution/src/MyProject/SharedFunctions.fs: -------------------------------------------------------------------------------- 1 | namespace App 2 | 3 | open System 4 | open System.Text.RegularExpressions 5 | 6 | [] 7 | module SharedFunctions = 8 | let (|ParseRegex|_|) regex str = 9 | let m = Regex(regex).Match(str) 10 | if m.Success then Some (List.tail [ for x in m.Groups -> x.Value ]) 11 | else None 12 | 13 | let (|IsNullOrWhiteSpace|_|) input = 14 | if String.IsNullOrWhiteSpace input then Some () 15 | else None 16 | 17 | let (|IsValidEmail|_|) input = 18 | match input with 19 | | ParseRegex ".*?@(.*)" [ _ ] -> Some input 20 | | _ -> None 21 | 22 | -------------------------------------------------------------------------------- /MySolution/tests/MyProjectTests/MyProjectTests.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | 6 | false 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | runtime; build; native; contentfiles; analyzers; buildtransitive 26 | all 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /MySolution/tests/MyProjectTests/Program.fs: -------------------------------------------------------------------------------- 1 | module Program = let [] main _ = 0 2 | -------------------------------------------------------------------------------- /MySolution/tests/MyProjectTests/Tests.fs: -------------------------------------------------------------------------------- 1 | module Tests 2 | 3 | open System 4 | open App 5 | open Xunit 6 | 7 | module AddCustomerTests = 8 | 9 | [] 10 | let validFirstName = "Geraldine" 11 | [] 12 | let validSurname = "Grainger-Tuppence" 13 | [] 14 | let validEmail = "geraldine@someimaginarycompany.co.uk" 15 | let validDateOfBirth = DateTime(1975, 1, 13) |> DateOnly.FromDateTime 16 | 17 | let nowProvider = fun () -> DateTime.Now 18 | 19 | let companyRepository id = 20 | Some { Id = id; Name = $"Some Imaginary Company"; Classification = Gold } 21 | 22 | let customerRepository (input:Customer * Company * CompanyCredit) = () 23 | 24 | let creditService (company:Company) = 1000 25 | 26 | let services = { 27 | NowProvider = nowProvider 28 | GetCompanyById = companyRepository 29 | CreateCustomer = customerRepository 30 | CreditCheckService = creditService 31 | } 32 | 33 | let rand = 34 | let rnd = Random() 35 | fun () -> rnd.Next(100) 36 | 37 | module ``Invalid Customer inputs`` = 38 | 39 | // TODO: full set of tests for invalid inputs 40 | 41 | [] 42 | let ``Invalid inputs returns expected errors`` () = 43 | let firstName = " " 44 | let surname = "Grainger-Tuppence" 45 | let email = "" 46 | let dateOfBirth = DateTime(1975, 1, 13) |> DateOnly.FromDateTime 47 | let companyId = 0 48 | 49 | let actual = 50 | CustomerService.addCustomer services firstName surname email dateOfBirth companyId 51 | 52 | let expected = Error (FailedCreateValidation [EmptyFirstName " "; InvalidEmail ""]) 53 | 54 | Assert.Equal(expected, actual) 55 | 56 | 57 | module ``Gold Company classification`` = 58 | 59 | [] 60 | let ``With valid inputs returns Ok`` () = 61 | let companyId = rand() 62 | 63 | let actual = 64 | CustomerService.addCustomer services validFirstName validSurname validEmail validDateOfBirth companyId 65 | 66 | let expected = Ok () 67 | 68 | Assert.Equal(expected, actual) 69 | 70 | 71 | module ``Non-Gold Company classification`` = 72 | 73 | [] 74 | let ``Silver company with sufficient credit and valid inputs returns Ok`` () = 75 | let companyId = rand() 76 | 77 | let silverCompanyRepository (id:int) = 78 | Some { Id = companyId; Name = $"Some Imaginary Company"; Classification = Silver } 79 | let services' = { services with GetCompanyById = silverCompanyRepository } 80 | 81 | let actual = 82 | CustomerService.addCustomer services' validFirstName validSurname validEmail validDateOfBirth companyId 83 | 84 | let expected = Ok () 85 | 86 | Assert.Equal(expected, actual) 87 | 88 | [] 89 | let ``Silver company with insufficient credit and valid inputs returns Ok`` () = 90 | let companyId = rand() 91 | 92 | let silverCompanyRepository (id:int) = 93 | Some { Id = companyId; Name = $"Some Imaginary Company"; Classification = Silver } 94 | let noCreditService (company:Company) = 0 95 | let services' = { services with GetCompanyById = silverCompanyRepository; CreditCheckService = noCreditService } 96 | 97 | let actual = 98 | CustomerService.addCustomer services' validFirstName validSurname validEmail validDateOfBirth companyId 99 | 100 | let expected = Ok () 101 | 102 | Assert.Equal(expected, actual) 103 | 104 | module ``Company not found`` = 105 | 106 | [] 107 | let ``returns expected error`` () = 108 | let companyId = 42 109 | 110 | let emptyCompanyRepository (id:int) = None 111 | let services' = { services with GetCompanyById = emptyCompanyRepository } 112 | 113 | let actual = 114 | CustomerService.addCustomer services' validFirstName validSurname validEmail validDateOfBirth companyId 115 | 116 | let expected = Error (CompanyNotFound companyId) 117 | 118 | Assert.Equal(expected, actual) 119 | 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # F# Example Codebase 2 | 3 | This is some code from converting an interview coding test from C# into F#. It makes use of the awesome FsToolkit.ErrorHandling package (). 4 | 5 | This codebase contains a number of F# features and techniques including: 6 | 7 | - Computation Expressions 8 | - Higher-Order Functions 9 | - Validation 10 | - Discriminated Unions 11 | - Single-case Discriminated Unions 12 | - Result and Option 13 | - Records and Tuples 14 | - Modules 15 | 16 | ## Free F# ebook 17 | 18 | To learn more about these features and a lot more, you can download my free 200-page ebook from 19 | 20 | ## Setting up 21 | 22 | This code was written using VS Code, the ionide F# extension, and .Net SDK 7.0.10. 23 | 24 | ## Running the code 25 | 26 | In the terminal, navigate to the project in the src folder and type: 27 | 28 | ```dotnet run``` 29 | 30 | In the terminal, you will get an output of ```Ok ()``` 31 | 32 | If you change some of the data to be invalid, say the FirstName to " " and the Email to "" and run again you will get an output of ```Error (FailedCreateValidation [EmptyFirstName " "; InvalidEmail ""])``` 33 | 34 | ## Running the tests 35 | 36 | Open a new terminal, navigate to the project in the tests folder and type: 37 | 38 | ```dotnet test``` 39 | 40 | In the terminal, you will get an output showing the result of running the tests. 41 | -------------------------------------------------------------------------------- /init.txt: -------------------------------------------------------------------------------- 1 | dotnet new sln -o MySolution 2 | cd MySolution 3 | mkdir src 4 | dotnet new console -lang F# -o src/MyProject 5 | dotnet sln add src/MyProject/MyProject.fsproj 6 | mkdir tests 7 | dotnet new xunit -lang F# -o tests/MyProjectTests 8 | dotnet sln add tests/MyProjectTests/MyProjectTests.fsproj 9 | cd tests/MyProjectTests 10 | dotnet add reference ../../src/MyProject/MyProject.fsproj 11 | dotnet add package Xunit 12 | dotnet add package FsUnit.XUnit 13 | dotnet build 14 | dotnet test --------------------------------------------------------------------------------