vkhorikov / CSharpFunctionalExtensions

Functional extensions for C#
MIT License
2.44k stars 304 forks source link

Question about Maybe and Enums #28

Closed solvingj closed 3 months ago

solvingj commented 7 years ago

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.

vkhorikov commented 7 years ago

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.

StefH commented 7 years ago

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

vkhorikov commented 7 years ago

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

StefH commented 7 years ago

Which types are not supported?

vkhorikov commented 7 years ago

Could you please elaborate?

solvingj commented 7 years ago

@StefH reference types, such as classes for example.

manuel-ornato commented 7 years ago

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?

vkhorikov commented 7 years ago

@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.

solvingj commented 7 years ago

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

bothzoli commented 3 months ago

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