CSharpFunctionalExtensions icon indicating copy to clipboard operation
CSharpFunctionalExtensions copied to clipboard

Question about Maybe and Enums

Open solvingj opened this issue 8 years ago • 9 comments

I think I just determined that Maybe can't be used to hold enum's because it can currently only hold reference types, is this correct?

If so, I think it's because you've constrained T to "class" specifically.

public struct Maybe<T> : IEquatable<Maybe<T>> where T : class

Can you think of any easy way to achieve an enum type in a Maybe?

For the record, I was trying to implement text parsing adapters for enums and other primitive types into Maybe's. The goal was similar to what was achieved here:

https://github.com/louthy/language-ext

If you scroll down, you can see how they replaced TryParse with parseInt that returns an option.

Interestingly, they did not do am implementation for parseEnum, but in theory they could have.

solvingj avatar Apr 21 '17 23:04 solvingj

You are right, Maybe in the current implementation is for reference types only. For Enums, I'd recommend using the built-in Nullable<> type. For example:

MyEnum? myEnum = MyEnum.SomeValue;

The compiler automatically transforms ? into Nullable<MyEnum> here.

vkhorikov avatar Apr 24 '17 20:04 vkhorikov

Indeed, why not just using Nullable<> instead of Maybe<> in all your code?

StefH avatar Apr 25 '17 07:04 StefH

@StefH because Nullable<> is restricted to only Value Types (structs).

vkhorikov avatar Apr 25 '17 10:04 vkhorikov

Which types are not supported?

StefH avatar Apr 26 '17 16:04 StefH

Could you please elaborate?

vkhorikov avatar Apr 26 '17 16:04 vkhorikov

@StefH reference types, such as classes for example.

solvingj avatar Apr 26 '17 21:04 solvingj

Same here, I often find myself stuck with patterns like: MaybeVar.Select(v => v.IntProp).Unwrap(42); (where MaybeVar is a Maybe<T> and IntProp is an int property of T) failing because of that limitation. So I have to go through if(MaybeVar.HasValue) ... that doesn't feel very 'Monadic'... The duality betwwen Maybe<RefType> and Nullable<ValType> doesn't seem to allow for fluent constructs. Or did I missed something?

manuel-ornato avatar May 03 '17 16:05 manuel-ornato

@manuel-ornato Great point. My initial inclination was that having two competing types (Nullable<> and Maybe<>) would bring confusion. But now that I think more about it, it makes sense to remove this limitation in order to enable fluent syntax with .NET value types.

I'll try to remove it soon and republish the package. @solvingJ , feel free to send a pull request too if you will.

vkhorikov avatar May 05 '17 02:05 vkhorikov

I think this makes a lot of sense. I'll give it a try ASAP.

solvingj avatar May 05 '17 20:05 solvingj

Maybe is now capable of holding and correctly handling enumeration types and other structure types, so I think this issue could be closed.

bothzoli avatar Jul 25 '24 11:07 bothzoli