├── some_text_file.txt ├── some_text_file.txt.prefixed ├── .editorconfig ├── SharpIO ├── SharpIO.csproj └── EnvIO.cs ├── FreeIO ├── FreeIO.csproj └── FreeIO.cs ├── Directory.Build.props ├── README.md ├── LICENSE ├── SharpIO.sln └── .gitignore /some_text_file.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 -------------------------------------------------------------------------------- /some_text_file.txt.prefixed: -------------------------------------------------------------------------------- 1 | 1: 1 2 | 2: 2 3 | 3: 3 4 | 4: 4 5 | 5: 5 6 | 6: 6 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | -------------------------------------------------------------------------------- /SharpIO/SharpIO.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | netcoreapp3.1 5 | latest 6 | 7 | 8 | -------------------------------------------------------------------------------- /FreeIO/FreeIO.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | latest 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | Maksim Volkau 4 | Copyright © 2017-2019 Maksim Volkau 5 | 6 | Latest 7 | 8 | true 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SharpIO 2 | 3 | Effect values for C# with examples, inspired by Haskell Free Monad and Scalaz ZIO 4 | 5 | Useful links: 6 | - [John DeGoes: Beyond Free Monads - λC Winter Retreat 2017](https://www.youtube.com/watch?v=A-lmrvsUi2Y) 7 | - [Free and tagless compared - how not to commit to a monad too early](https://softwaremill.com/free-tagless-compared-how-not-to-commit-to-monad-too-early) 8 | - [Original Free Monad in C# gist by @louthy](https://gist.github.com/louthy/524fbe8965d3a2aae1b576cdd8e971e4) 9 | - [FP extensions for C# by @louthy](https://github.com/louthy/language-ext) 10 | - [John A De Goes - ZIO: Next-Generation Effects in Scala 2019](https://www.youtube.com/watch?v=mkSHhsJXjdc) 11 | - [ZIO Environment](http://degoes.net/articles/zio-environment) 12 | - [Testable ZIO](http://degoes.net/articles/testable-zio) 13 | - [F# ZIO demo by @AnthonyLloyd](https://gist.github.com/dadhi/27c44a264a61dfa1d8fce692bccac32e) 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Maksim Volkau 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /SharpIO.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.421 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpIO", "SharpIO\SharpIO.csproj", "{B572C40D-1657-46E6-A4FD-2BDB26A1D9E0}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FreeIO", "FreeIO\FreeIO.csproj", "{F4EAD5FD-41A9-45D1-ACF2-788D20738314}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{919127BF-66EA-42DA-8645-9011603BDC6C}" 11 | ProjectSection(SolutionItems) = preProject 12 | Directory.Build.props = Directory.Build.props 13 | LICENSE = LICENSE 14 | README.md = README.md 15 | EndProjectSection 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {B572C40D-1657-46E6-A4FD-2BDB26A1D9E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {B572C40D-1657-46E6-A4FD-2BDB26A1D9E0}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {B572C40D-1657-46E6-A4FD-2BDB26A1D9E0}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {B572C40D-1657-46E6-A4FD-2BDB26A1D9E0}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {F4EAD5FD-41A9-45D1-ACF2-788D20738314}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {F4EAD5FD-41A9-45D1-ACF2-788D20738314}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {F4EAD5FD-41A9-45D1-ACF2-788D20738314}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {F4EAD5FD-41A9-45D1-ACF2-788D20738314}.Release|Any CPU.Build.0 = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(SolutionProperties) = preSolution 33 | HideSolutionNode = FALSE 34 | EndGlobalSection 35 | GlobalSection(ExtensibilityGlobals) = postSolution 36 | SolutionGuid = {9F5DF5A2-CB89-43AF-ABC6-65B3C0290DF4} 37 | EndGlobalSection 38 | EndGlobal 39 | -------------------------------------------------------------------------------- /.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/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /FreeIO/FreeIO.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Modified from the original https://gist.github.com/louthy/524fbe8965d3a2aae1b576cdd8e971e4 3 | 4 | - removed dependency on [language-ext](https://github.com/louthy/language-ext) 5 | - separated monadic boilerplate, so you may concentrate on describing the operations and interpretation of the program 6 | - removed `IO.Faulted` to simplify the examples. It can be added back in straightforward manner. 7 | 8 | Useful links: 9 | - [John DeGoes: Beyond Free Monads - λC Winter Retreat 2017](https://www.youtube.com/watch?v=A-lmrvsUi2Y) 10 | - [Free and Tagless compared - how not to commit to a monad too early](https://softwaremill.com/free-tagless-compared-how-not-to-commit-to-monad-too-early) 11 | - [John A De Goes - ZIO: Next-Generation Effects in Scala 2019](https://www.youtube.com/watch?v=mkSHhsJXjdc) 12 | 13 | Requires C# 7.2 14 | For `LiveRunner` to work you need "d:/some_text_file.txt" with couple of lines of text 15 | */ 16 | 17 | using System; 18 | using System.Collections.Generic; 19 | using System.IO; 20 | using System.Linq; 21 | using System.Threading.Tasks; 22 | 23 | namespace FreeIO 24 | { 25 | using static None; 26 | using static NumberLinesOperations; 27 | 28 | public class Program 29 | { 30 | public static async Task Main() 31 | { 32 | // Describe program without running it: 33 | var program = NumberLines(@"C:\Dev\SharpIO\some_text_file.txt"); 34 | 35 | // Actually running the program using different runners (interpreters): 36 | Console.WriteLine("## TestRunner"); 37 | TestRunner.Run(program); 38 | 39 | Console.WriteLine("## Empty runner"); 40 | TestRunner.Run(program, skipLogging: true); 41 | 42 | Console.WriteLine("## LiveRunner"); 43 | LiveRunner.Run(program); 44 | 45 | Console.WriteLine("## AsyncRunner"); 46 | await AsyncRunner.Run(program); 47 | } 48 | 49 | // Program description 50 | private static IO NumberLines(string path) => 51 | from lines in ReadAllLines(path) 52 | from logLineCount in Log($"There are {lines.Count()} lines") 53 | from logHeader in Log("Pre-pending the line numbers") 54 | let newLines = Enumerable.Range(1, int.MaxValue).Zip(lines, (i, line) => $"{i}: {line}") 55 | let newFile = path + ".prefixed" 56 | from flushLines in WriteAllLines(newFile, newLines) 57 | from logSuccess in Log($"Lines prepended and file saved successfully to '{newFile}'") 58 | select none; 59 | } 60 | 61 | public readonly struct WriteAllLines : IOut 62 | { 63 | public readonly string Path; 64 | public readonly IEnumerable Lines; 65 | public WriteAllLines(string path, IEnumerable lines) => (Path, Lines) = (path, lines); 66 | } 67 | 68 | public readonly struct ReadAllLines : IOut> 69 | { 70 | public readonly string Path; 71 | public ReadAllLines(string path) => Path = path; 72 | } 73 | 74 | public readonly struct Log : IOut 75 | { 76 | public readonly string Message; 77 | public Log(string message) => Message = message; 78 | } 79 | 80 | // todo: @api simplify please 81 | public static class NumberLinesOperations 82 | { 83 | public static IO WriteAllLines(string path, IEnumerable lines) => 84 | new WriteAllLines(path, lines).ToIO(); 85 | 86 | public static IO> ReadAllLines(string path) => 87 | new ReadAllLines(path).ToIO>(); // todo: @api how to help the inference - default intreface impl or conversion operator? 88 | 89 | public static IO Log(string message) => 90 | new Log(message).ToIO(); 91 | } 92 | 93 | public static class LiveRunner 94 | { 95 | public static A Run(IO program) 96 | { 97 | switch (program) 98 | { 99 | case P.Of> p: 100 | return Run(p.Step(TestRunner.ReadAllLines(p.Input.Path))); 101 | 102 | case P.Of p: 103 | return Run(p.Wrap(x => TestRunner.WriteAllLines(x.Path, x.Lines))); 104 | 105 | case P.Of p: 106 | return Run(p.Wrap(log => Console.WriteLine(log.Message))); 107 | 108 | default: 109 | return program.Result(); 110 | } 111 | } 112 | } 113 | 114 | public static class AsyncRunner 115 | { 116 | public static IEnumerable ReadAllLines(string path) => new[] { "Hello", "World", path }; 117 | public static Task> ReadAllLinesAsync(string path) => Task.FromResult(ReadAllLines(path)); 118 | public static Task WriteAllLinesAsync(string path, IEnumerable content) => Task.CompletedTask; 119 | public static async Task Run(IO program) 120 | { 121 | switch (program) 122 | { 123 | case P.Of> p: 124 | return await Run(p.Step(await ReadAllLinesAsync(p.Input.Path))); 125 | 126 | case P.Of p: 127 | return await Run(p.Wrap(async x => await WriteAllLinesAsync(x.Path, x.Lines))); 128 | 129 | case P.Of p: 130 | return await Run(p.Wrap(log => Console.WriteLine(log.Message))); 131 | 132 | default: 133 | return program.Result(); 134 | } 135 | } 136 | } 137 | 138 | public static class TestRunner 139 | { 140 | public static IEnumerable ReadAllLines(string path) => new[] { "Hello", "World", path }; 141 | public static void WriteAllLines(string path, IEnumerable content) {} 142 | 143 | // Example of non-recursive (stack-safe) runner 144 | public static A Run(IO program, bool skipLogging = false) 145 | { 146 | while (true) 147 | switch (program) 148 | { 149 | case P.Of> p: 150 | program = p.Step(ReadAllLines(p.Input.Path)); 151 | break; 152 | case P.Of p: 153 | program = p.Step(); 154 | break; 155 | case P.Of p: 156 | program = skipLogging ? p.Step() : p.Wrap(x => Console.WriteLine(x.Message)); 157 | break; 158 | default: 159 | return program.Result(); 160 | } 161 | } 162 | } 163 | 164 | // Monadic IO implementation, can be reused, published to NuGet, etc. 165 | //------------------------------------------------------------------- 166 | 167 | /// Operation with the result 168 | public interface IOut 169 | { 170 | } 171 | 172 | public interface IO 173 | { 174 | IO Bind(Func> f); 175 | } 176 | 177 | public readonly struct Return : IO 178 | { 179 | public readonly A Result; 180 | public Return(A a) => Result = a; 181 | public IO Bind(Func> f) => f(Result); 182 | } 183 | 184 | public static class P 185 | { 186 | public class Of : IO where I : IOut 187 | { 188 | public readonly I Input; 189 | public readonly Func> Step; 190 | public Of(I input, Func> step) => (Input, Step) = (input, step); 191 | public IO Bind(Func> f) => new P.Of(Input, o => Step(o).Bind(f)); 192 | } 193 | 194 | public class Of : IO where I : IOut 195 | { 196 | public readonly I Input; 197 | public readonly Func> Step; 198 | public Of(I input, Func> step) => (Input, Step) = (input, step); 199 | public IO Bind(Func> f) => new P.Of(Input, () => Step().Bind(f)); 200 | } 201 | } 202 | 203 | public static class IOMonad 204 | { 205 | public static Func> Free(Func> io, Func> f) => 206 | o => io(o).Bind(f); 207 | 208 | public static IO Return(this A a) => new Return(a); 209 | 210 | public static IO Select(this IO m, Func f) => 211 | m.Bind(a => f(a).Return()); 212 | 213 | public static IO SelectMany(this IO m, Func> f, Func project) => 214 | m.Bind(a => f(a).Bind(b => project(a, b).Return())); 215 | 216 | public static A Result(this IO m) => ((Return)m).Result; 217 | } 218 | 219 | public static class IOMonadSugar 220 | { 221 | public static IO ToIO(this I input) where I : IOut => 222 | new P.Of(input, IOMonad.Return); 223 | 224 | public static IO ToIO(this I input) where I : IOut => 225 | new P.Of(input, () => new Return()); 226 | 227 | public static IO Wrap(this P.Of io, Action effect) where I : IOut 228 | { 229 | effect(io.Input); 230 | return io.Step(); 231 | } 232 | } 233 | 234 | public struct None 235 | { 236 | public static readonly None none = new None(); 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /SharpIO/EnvIO.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace SharpIODemo 5 | { 6 | using System; 7 | using SharpIO; 8 | using static SharpIO.Result; 9 | using static SharpIO.IO; 10 | 11 | public class Program 12 | { 13 | public static void Main() 14 | { 15 | var game = CreateGame(); 16 | 17 | var expected = game.Run(new Env(new TestConsole("OnepunchMan"), new TestLog())); 18 | 19 | Console.WriteLine(expected); 20 | } 21 | 22 | public static IO CreateGame() => 23 | from logStart in Log.Info("Starting the quiz...") 24 | from askForName in Out.WriteLine("Enter your name:") 25 | from name in Out.ReadLine() 26 | from logName in Log.Info($"Your name is {name}") 27 | select name; 28 | 29 | public sealed class Env : IWithLog, IWithConsole 30 | { 31 | public IConsole Console { get; } 32 | public ILog Log { get; } 33 | public Env(IConsole console, ILog log) => (Console, Log) = (console, log).EnsureNotNull(); 34 | } 35 | } 36 | 37 | public interface IConsole 38 | { 39 | IO WriteLine(string line); 40 | IO ReadLine(); 41 | } 42 | 43 | public interface IWithConsole 44 | { 45 | IConsole Console { get; } 46 | } 47 | 48 | public interface ILog 49 | { 50 | IO Info(string message); 51 | } 52 | 53 | public interface IWithLog 54 | { 55 | ILog Log { get; } 56 | } 57 | 58 | public class TestConsole : IConsole 59 | { 60 | private readonly string _output; 61 | 62 | public TestConsole(string output = default) => _output = output ?? "Wizard"; 63 | 64 | public IO WriteLine(string line) => DoNothing(); 65 | 66 | public IO ReadLine() => 67 | Success(_output, default(Exception)).ToIO(); 68 | } 69 | 70 | public class TestLog : ILog 71 | { 72 | public IO Info(string message) => DoNothing(); 73 | } 74 | 75 | public static class Out where TEnv : IWithConsole 76 | { 77 | public static IO WriteLine(string line) => 78 | Use().To(e => e.Console.WriteLine(line)); 79 | 80 | public static IO ReadLine() => 81 | Use().To(e => e.Console.ReadLine()); 82 | } 83 | 84 | public static class Log where TEnv : IWithLog 85 | { 86 | public static IO Info(string message) => 87 | Use().To(e => e.Log.Info(message)); 88 | } 89 | } 90 | 91 | namespace SharpIO 92 | { 93 | using System; 94 | using static Nothing; 95 | using static Result; 96 | 97 | // ReSharper disable UnusedTypeParameter 98 | 99 | public abstract class CannotFail 100 | { 101 | private CannotFail() { } 102 | } 103 | 104 | public readonly struct Nothing 105 | { 106 | public static readonly Nothing nothing = new Nothing(); 107 | } 108 | 109 | public interface IResult { } 110 | 111 | public readonly struct Success : IResult 112 | { 113 | public readonly TVal Value; 114 | public Success(TVal value) => Value = value; 115 | 116 | /// Helping the inference 117 | public IO ToIO() => this.ToIO(); 118 | 119 | public override string ToString() => "success: " + Value; 120 | } 121 | 122 | public readonly struct Failure : IResult 123 | { 124 | public readonly TErr Error; 125 | public Failure(TErr error) => Error = error; 126 | 127 | public Failure FailFor() => new Failure(Error); 128 | 129 | public override string ToString() => "failure! " + Error; 130 | } 131 | 132 | public static class Result 133 | { 134 | public static Success Success(TVal value, TErr _ = default) => 135 | new Success(value); 136 | 137 | public static Success Success() => 138 | new Success(nothing); 139 | 140 | public static IResult Success(TVal value) => 141 | new Success(value); 142 | 143 | public static Success Success() => SuccessEmpty; 144 | public static readonly Success SuccessEmpty = 145 | new Success(nothing); 146 | 147 | public static IResult Failure(TErr error, TVal _ = default) => 148 | new Failure(error); 149 | 150 | public static IResult Failure(TErr error) => 151 | new Failure(error); 152 | 153 | public static IResult Map(this IResult a, Func map) => 154 | a is Success success 155 | ? (IResult)Success(map(success.Value)) 156 | : ((Failure)a).FailFor(); 157 | } 158 | 159 | public interface IO 160 | { 161 | Func> Run { get; } 162 | } 163 | 164 | public interface IO : IO {} 165 | 166 | public interface IO : IO {} 167 | 168 | public struct EnvIO : IO 169 | { 170 | public Func> Run { get; } 171 | public EnvIO(Func> run) => Run = run; 172 | } 173 | 174 | public struct EnvIO : IO 175 | { 176 | public Func> Run { get; } 177 | public EnvIO(Func> run) => Run = run; 178 | } 179 | 180 | public static class IO 181 | { 182 | static IResult Run(this IResult result, TEnv _ = default) => 183 | result; 184 | 185 | public static IO ToIO(this IResult result) => 186 | new EnvIO(result.Run); 187 | 188 | public static IO DoNothingOrFail() => 189 | new EnvIO(((IResult)Success()).Run); 190 | 191 | public static IO DoNothing() => 192 | new EnvIO(((IResult)Success()).Run); 193 | 194 | public static IO Use() => 195 | new EnvIO(env => Success(env, default(TErr))); 196 | 197 | public static IO Use() => 198 | new EnvIO(Success); 199 | 200 | public static IO To( 201 | this IO aCannotFail, Func> map) => 202 | new EnvIO(env => 203 | { 204 | var aSuc = (Success)aCannotFail.Run(env); 205 | var b = map(aSuc.Value); 206 | return b.Run(env); 207 | }); 208 | 209 | public static IO To( 210 | this IO aCannotFail, Func> map) => 211 | new EnvIO(env => 212 | { 213 | var aSuc = (Success)aCannotFail.Run(env); 214 | var b = map(aSuc.Value); 215 | return b.Run(env); 216 | }); 217 | 218 | public static IO To( 219 | this IO a, Func> map) => 220 | new EnvIO(env => 221 | { 222 | var aRes = a.Run(env); 223 | if (aRes is Success aSuc) 224 | { 225 | var bCannotFail = map(aSuc.Value); 226 | var bSuc = (Success)bCannotFail.Run(env); 227 | return new Success(bSuc.Value); 228 | } 229 | 230 | return ((Failure)aRes).FailFor(); 231 | }); 232 | 233 | public static IO To( 234 | this IO a, Func> map) => 235 | new EnvIO(env => 236 | { 237 | var aRes = a.Run(env); 238 | if (aRes is Success aSuc) 239 | return map(aSuc.Value).Run(env); 240 | 241 | return ((Failure)aRes).FailFor(); 242 | }); 243 | } 244 | 245 | public static class IOLinq 246 | { 247 | public static IO Select( 248 | this IO a, Func map) => 249 | new EnvIO(env => a.Run(env).Map(map)); 250 | 251 | public static IO SelectMany( 252 | this IO aCannotFail, Func> map, Func project) 253 | { 254 | return new EnvIO(env => 255 | { 256 | var aSuc = (Success)aCannotFail.Run(env); 257 | var b = map(aSuc.Value); 258 | var bSuc = (Success)b.Run(env); 259 | return new Success(project(aSuc.Value, bSuc.Value)); 260 | }); 261 | } 262 | 263 | public static IO SelectMany( 264 | this IO aCannotFail, Func> map, Func project) 265 | { 266 | return new EnvIO(env => 267 | { 268 | var aSuc = (Success)aCannotFail.Run(env); 269 | var b = map(aSuc.Value); 270 | var bRes = b.Run(env); 271 | if (bRes is Success bSuc) 272 | return new Success(project(aSuc.Value, bSuc.Value)); 273 | 274 | return ((Failure)bRes).FailFor(); 275 | }); 276 | } 277 | 278 | public static IO SelectMany( 279 | this IO a, Func> map, Func project) => 280 | new EnvIO(env => 281 | { 282 | var aRes = a.Run(env); 283 | if (aRes is Success aSuc) 284 | { 285 | var bCannotFail = map(aSuc.Value); 286 | var bSuc = (Success)bCannotFail.Run(env); 287 | return new Success(project(aSuc.Value, bSuc.Value)); 288 | } 289 | 290 | return ((Failure)aRes).FailFor(); 291 | }); 292 | 293 | public static IO SelectMany( 294 | this IO a, Func> map, Func project) => 295 | new EnvIO(env => 296 | { 297 | var aRes = a.Run(env); 298 | if (aRes is Success aSuc) 299 | { 300 | var b = map(aSuc.Value); 301 | var bRes = b.Run(env); 302 | if (bRes is Success bSuc) 303 | return new Success(project(aSuc.Value, bSuc.Value)); 304 | 305 | return ((Failure)bRes).FailFor(); 306 | } 307 | 308 | return ((Failure)aRes).FailFor(); 309 | }); 310 | } 311 | 312 | public static class Ensure 313 | { 314 | public static (T1, T2) EnsureNotNull(in this (T1, T2) x) => 315 | x.Item1 is null ? throw new ArgumentNullException("???", $"arg0 of '{typeof(T1)}' should not be null") : 316 | x.Item2 is null ? throw new ArgumentNullException("???", $"arg1 is '{typeof(T2)}' should not be null") : 317 | x; 318 | } 319 | } 320 | --------------------------------------------------------------------------------