Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ equivalent of f#'s builder.Zero()?

Tags:

c#

monoids

f#

So, I've become quite addicted to f#'s computation expressions and custom builders. I have to use c# for most of my daily work but still want to use LINQ expressions with my own monads/monoids. Does anybody know if there's a c# analog to f#'s Zero method?

Relevant f# docs

Here's what I do in f#:

type OptionBuilder() =
    member x.Bind(v,f) = Option.bind f v
    member x.Return v = Some v
    member x.ReturnFrom o = o
    member x.Zero() = Option.None

let option = OptionBuilder()

// Example usage (I want something similar from c#)

let t : Option<int> =
    option { if false then return 5 }
like image 325
Jonathan Wilson Avatar asked Dec 15 '22 01:12

Jonathan Wilson


1 Answers

I'm not sure exactly what you're asking here but I'll give it a shot. Consider clarifying the question.

The equivalent in C# to an if with no else in a monadic workflow is:

from a in b
where c(a)
select a

Logically this is equivalent to (using your Bind, Return and Zero)

Bind(b, a => c(a) ? Return(a) : Zero)

But C# does not lower a where clause into a SelectMany (which is what C# calls Bind). C# lowers a Where clause in a query comprehension to a call to

Where(M<T>, Func<T, bool>)

In short: C# has arbitrary monadic workflows in the form of query comprehensions; any monadic type with the Select, SelectMany, Where, etc, methods can be used in a comprehension. But it doesn't really generalize to additive monads with an explicit zero. Rather, "Where" is expected to have the semantics of the bind operation I noted above: it should have the same effect as binding a single value onto the end if the item matches the predicate, and the zero value if not.

Plainly "Where" for sequences does that. If you have [a, b, c] and want to filter out b, that's the same as concatenating together [[a], [], [c]]. But of course it would be crazily inefficient to actually build and concatenate all those little sequences. The effect has to be the same, but the actual operations can be much more efficient.

C# is really designed to have support for very specific monads: the sequence monad via yield and query comprehensions, the continuation comonad via await, and so on. We didn't design it to enable arbitrary monadic workflows as you see in Haskell.

Does that answer your question?

like image 160
Eric Lippert Avatar answered Dec 17 '22 02:12

Eric Lippert