Is there a reason workflow builders in F# don't use interfaces?
This is a question just out of curiosity: when you implement a workflow factory, you don't do it as an interface implementation, but rather just make sure the function signatures of the monad functions match. Is there a design开发者_如何学编程 reason for this?
For one thing, the lack of higher-kinded types in .NET means that you can't give the methods useful signatures. For instance, ListBuilder.Return
should have type 't -> 't list
, while OptionBuilder.Return
should have type 't -> 't option
. There's no way to create an interface with a Return
method that has a signature supporting both of these methods.
I think that the lack of higher-kinded types as mentioned by kvb is probably the main reason. There are ways to workaround that, but that makes the code a bit obscure (see this snippet).
Another reason is that F# computation expressions allow you to define different combinations of methods. It's not always just Bind
and Return
. For example:
- Some define
Yield
,YieldFrom
,Combine
to allow generating results - Some define
Return
,ReturnFrom
,Bind
to define a monad - Some define
Return
,ReturnFrom
,Bind
,Combine
to define a monad that can return multiple things - Some also define
Delay
orDelay
andRun
to handle laziness
... so computation expressions would need to be defined as quite a few different interfaces. I think the current design leaves some nice flexibility in what features of computations you can support.
精彩评论