Skip to content

Instantly share code, notes, and snippets.

@aswhitehouse
Created July 14, 2018 05:13
Show Gist options
  • Save aswhitehouse/d0371cbae1cdf216c83093fe2f973360 to your computer and use it in GitHub Desktop.
Save aswhitehouse/d0371cbae1cdf216c83093fe2f973360 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ArrayStructure
{
public struct Maybe<T>
{
readonly IEnumerable<T> values;
public static Maybe<T> Some(T value)
{
if (value == null)
{
throw new InvalidOperationException();
}
return new Maybe<T>(new[] {value});
}
public static Maybe<T> None => new Maybe<T>(new T[0]);
Maybe(IEnumerable<T> values)
{
this.values = values;
}
public bool HasValue => values != null && values.Any();
public T Value
{
get
{
if (!HasValue)
{
throw new InvalidOperationException("Maybe does not have a value");
}
return values.Single();
}
}
public T ValueOrDefault(T @default)
{
if (!HasValue)
{
return @default;
}
return values.Single();
}
public T ValueOrThrow(Exception e)
{
if (HasValue)
{
return Value;
}
throw e;
}
public U Case<U>(Func<T, U> some, Func<U> none)
{
return HasValue
? some(Value)
: none();
}
public void Case(Action<T> some, Action none)
{
if (HasValue)
{
some(Value);
}
else
{
none();
}
}
public void IfSome(Action<T> some)
{
if (HasValue)
{
some(Value);
}
}
public Maybe<U> Map<U>(Func<T, Maybe<U>> map)
{
return HasValue
? map(Value)
: Maybe<U>.None;
}
public Maybe<U> Map<U>(Func<T, U> map)
{
return HasValue
? Maybe.Some(map(Value))
: Maybe<U>.None;
}
}
public static class Maybe
{
public static Maybe<T> Some<T>(T value)
{
return Maybe<T>.Some(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment