I'm using the TryAsync
monad in LanguageExt, but am having difficulties trying to bind multiple ones together. I'm still learning functional programming, and so could be doing this completely wrongly. Please feel free to comment on any part of my approach here.
Suppose I have the following methods that call the Google Drive API...
TryAsync<File> GetFolder(string folderId)
TryAsync<string> CreateFolder(string folderName, string parentFolderId)
TryAsync<string> UploadFile(Stream file, string fileName, string mimeType, string folderId)
...where File
is a Google type for files/folders in a Google Drive.
I can call each of these individually, no problem, and can use Match
to handle the result.
However, I sometimes want to call more than one, say to get the File
object for a specific folder, then create a new subfolder and upload a file to it. I know I can do this as follows (air code, so please ignore any typos)...
(await GetFolder("123"))
.Match(async folder => {
(await CreateFolder("New folder", folder.Id))
.Match(async newFolder => {
(await UploadFile(stream, "New file name.txt", "text/text", newFolder.Id))
.Match(fileId => /* do whatever with the uploaded file's Id */, ex => /* report exception */);
}, ex => /* report exception */);
}, ex => /* report exception */);
As you can see, this is very painful. I am sure that you are supposed to be able to chain monads together, I think using Bind
, so you end up with something more like this (again, air code)...
(await GetFolder("123"))
.Bind(folder => CreateFolder("New folder", folder.Id))
.Bind(newFolder => UploadFile(stream, "New file name.txt", "text/text", newFolder.Id))
.Match(fileId => /* do whatever with the uploaded file's Id */, ex => /* report exception */);
However, I can't get any code to compile like this.
One problem is that I'm not sure if my methods have the right signature. Should they return Task<T>
, and have the calling code use TryAsync<T>
, or am I right in having the methods themselves return TryAsync<T>
?
Anyone able to advise how I should do this? Thanks