fpdart 0.0.5 fpdart: ^0.0.5 copied to clipboard
Functional programming in Dart and Flutter. All the main functional programming types and patterns fully documented, tested, and with examples.
import 'package:fpdart/fpdart.dart';
void main() {}
void option() {
/// Create an instance of [Some]
final option = Option.of(10);
/// Create an instance of [None]
final none = Option<int>.none();
/// Map [int] to [String]
final map = option.map((a) => '$a');
/// Extract the value from [Option]
final value = option.getOrElse(() => -1);
/// Pattern matching
final match = option.match(
(a) => print('Some($a)'),
() => print('None'),
);
/// Convert to [Either]
final either = option.toEither(() => 'missing');
/// Chain computations
final flatMap = option.flatMap((a) => Option.of(a + 10));
/// Return [None] if the function throws an error
final tryCatch = Option.tryCatch(() => int.parse('invalid'));
}
void either() {
/// Create an instance of [Right]
final right = Either<String, int>.of(10);
/// Create an instance of [Left]
final left = Either<String, int>.left('none');
/// Map the right value to a [String]
final mapRight = right.map((a) => '$a');
/// Map the left value to a [int]
final mapLeft = right.mapLeft((a) => a.length);
/// Return [Left] if the function throws an error.
/// Otherwise return [Right].
final tryCatch = Either.tryCatch(
() => int.parse('invalid'),
(e, s) => 'Error: $e',
);
/// Extract the value from [Either]
final value = right.getOrElse((l) => -1);
/// Chain computations
final flatMap = right.flatMap((a) => Either.of(a + 10));
/// Pattern matching
final match = right.match(
(l) => print('Left($l)'),
(r) => print('Right($r)'),
);
/// Convert to [Option]
final option = right.toOption();
}