3

I would like to write a SelectMany monadic bind from a Task in F#. How would I write the following C# code which uses language-ext in F#?

Task<int> result = from task in Task.Run<int>(() => 40) select task + 2;

Mike Harris
  • 869
  • 9
  • 21
  • 1
    What are you trying to do? This doesn't compile in C# and would be really weird even if it did. It's not a `SelectMany` either, just a `Select`. – Panagiotis Kanavos Jul 07 '20 at 11:55
  • If you have an iterator that produces values asynchronously, you should be using `IAsyncEnumerable` in C#. The equivalent in F# is provided by the [AsyncSeq](https://fsprojects.github.io/FSharp.Control.AsyncSeq/) library – Panagiotis Kanavos Jul 07 '20 at 11:58
  • @PanagiotisKanavos you are right! The example C# code I was using was not even correct! – Mike Harris Jul 07 '20 at 17:57
  • changed description to say that it works with language-ext for C#. If you the reader, find yourself here and do not understand what a monadic bind is, this is a great example http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html (it uses Haskell but I think is one of the best examples I've seen). – Mike Harris Jul 07 '20 at 21:25

1 Answers1

4

You can use the F# TaskBuilder library to get the F# computation expression (monadic syntax) for tasks. With this, you can rewrite your example as:

let result = task {
  let! t = Task.Run<int>(() => 40)
  return t + 2 }
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553