Skip to content

Instantly share code, notes, and snippets.

@pianostringquartet
Created October 16, 2018 10:30
Show Gist options
  • Save pianostringquartet/ccd741b6879e53524b0c1b416302d8f3 to your computer and use it in GitHub Desktop.
Save pianostringquartet/ccd741b6879e53524b0c1b416302d8f3 to your computer and use it in GitHub Desktop.
A pseudo console for Dart, using Dartpad (includes our Option type)
main() {
// Press `run` button to evaluate the file.
// You must explicitly print values, e.g. print("$myValue")
}
// CODE BELOW FOR OUR OPTION TYPE:
A identity<A>(A value) => value;
abstract class Option<A> {
const Option();
factory Option.of(A value) => value != null ? Some<A>(value) : empty();
static Option<A> empty<A>() => None<A>();
B fold<B>(B ifNone(), B ifSome(A value));
Option<B> map<B>(B f(A value)) => fold(empty, (value) => Some(f(value)));
Option<B> flatMap<B>(Option<B> f(A value)) =>
fold(empty, (value) => f(value));
Option<B> andThen<B>(Option<B> value) => fold(empty, (_) => value);
Option<A> filter(bool f(A value)) =>
fold(() => this, (value) => f(value) ? this : empty());
Option<A> orElse(Option<A> fallback()) =>
fold(fallback, (value) => Some(value));
A getOrElse(A fallback()) => fold(fallback, identity);
bool isDefined() => fold(() => false, (_) => true);
bool isEmpty() => !isDefined();
// REMOVED:
// Either<B, A> toEither<B>(B fallback()) =>
// fold(() => Left(fallback()), (value) => Right(value));
List<A> toList() => fold(() => const [], (value) => [value]);
A orNull() => fold(() => null, identity);
/// Returns `true` if this is a `Some` and its value is equal to `reference`
/// (as determined by `==`), returns `false` otherwise.
bool contains(A reference()) =>
fold(() => false, (value) => value == reference());
/// Returns `true` if `None` or returns the result of the application of
/// the given predicate to the `Some` value.
bool forall(bool reference(A a)) =>
fold(() => true, (value) => reference(value));
/// Returns `false` if `None` or returns the result of the application of
/// the given predicate to the `Some` value.
bool exists(bool reference(A a)) =>
fold(() => false, (value) => reference(value));
}
class Some<A> extends Option<A> {
final A value;
const Some(this.value) : super();
@override
B fold<B>(B ifNone(), B ifSome(A value)) => ifSome(value);
@override
bool operator ==(Object other) => other is Some && other.value == value;
@override
int get hashCode => value.hashCode;
@override
String toString() => 'Some<$A>($value)';
}
class None<A> extends Option<A> {
const None();
@override
B fold<B>(B ifNone(), B ifSome(A value)) => ifNone();
@override
bool operator ==(Object other) => other is None;
@override
int get hashCode => 0;
@override
String toString() => 'None<$A>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment