Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active July 4, 2024 18:21
Show Gist options
  • Save reidev275/dd57c807a8db6ac2189a672c8b32a348 to your computer and use it in GitHub Desktop.
Save reidev275/dd57c807a8db6ac2189a672c8b32a348 to your computer and use it in GitHub Desktop.
public interface IMaybe<T>
{
IMaybe<U> Map<U>(Func<T, U> func);
IMaybe<U> Bind<U>(Func<T, IMaybe<U>> func);
IMaybe<T> Filter(Func<T, bool> predicate);
IMaybe<T> Do(Action<T> just, Action nothing);
IMaybe<U> Do(Func<T, U> just, Action<U> nothing);
}
class Just<T> : IMaybe<T>
{
readonly T _obj;
public Just(T obj)
{
_obj = obj;
}
public IMaybe<U> Bind<U>(Func<T, IMaybe<U>> func)
{
return func(_obj);
}
public IMaybe<U> Map<U>(Func<T, U> func)
{
return new Some<U>(func(_obj));
}
public IMaybe<T> Filter(Func<T, bool> predicate)
{
return predicate(_obj)
? this
: new Nothing<T>();
}
public IMaybe<T> Do(Action<T> just, Action nothing)
{
just(_obj);
return this;
}
public IMabye<U> Do(Func<T, U> just, Action<U> nothing)
{
return just(_obj);
}
}
class Nothing<T> : IMaybe<T>
{
public IMaybe<U> Bind<U>(Func<T, IMaybe<U>> func)
{
return new Nothing<U>();
}
public IMaybe<U> Map<U>(Func<T, U> func)
{
return new Nothing<U>();
}
public IMaybe<T> Filter(Func<T, bool> predicate)
{
return this;
}
public IMaybe<T> Do(Action<T> _just, Action nothing)
{
nothing();
return this;
}
public IMabye<U> Do(Func<T, U> just, Action<U> nothing)
{
return nothing();
}
}
public static class IEnumerableExtensions
{
public static IMaybe<T> Head<T>(this IEnumerable<T> list)
{
var result = list.FirstOrDefault();
if (result == null) return new Nothing<T>();
return new Just(result);
}
}
new List<string>()
.Head()
.Do(
just => Console.WriteLine("The head was " + just),
() => Console.WriteLine("Cannot take the head of an empty list"));
@IEvangelist
Copy link

IEvangelist commented Aug 12, 2017

Hi, thank you for sharing this!

I have a few questions that I hope you can clear up... thank you in advance.

Where does the type Some on line 24 come from? Likewise the variable some on line 36 is not actually defined anywhere -- where does that come from? Why does the parameter, namely _just have the underscore prefix? Why does the parameter of nothing in the Just<T> impl not being used, is that supposed to be the some? Why does the Nothing<T> impl invoke the Action nothing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment