Skip to content

Commit

Permalink
#71 divide examples (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
SandroMaglione committed Dec 7, 2022
2 parents 80dac46 + 1ac7f32 commit 872f1b5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 22 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.dart_tool/
.packages
.packages
.idea/
19 changes: 9 additions & 10 deletions example/src/either/overview.dart
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import 'package:fpdart/fpdart.dart';

/// Don't do that! ⚠
double divideI(int x, int y) {
if (y == 0) {
throw Exception('Cannot divide by 0!');
}
int divideI(int x, int y) => x ~/ y; // this will throw if y == 0

return x / y;
}

/// Error handling using [Either] 🎉
Either<String, double> divideF(int x, int y) {
/// Error handling without exceptions using [Either] 🎉
Either<String, int> divideF(int x, int y) {
if (y == 0) {
return left('Cannot divide by 0');
}
return right(x ~/ y);
}

return right(x / y);
/// Error handling with exceptions using [Either] 🎉
Either<String, int> divide2F(int x, int y) {
/// Easy way with caveat: first param type 'object' due to dart limitation
return Either.tryCatch(() => x ~/ y, (o, s) => o.toString());
}

void main() {
Expand Down
18 changes: 7 additions & 11 deletions example/src/option/overview.dart
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import 'package:fpdart/fpdart.dart';

/// Don't do that! ⚠
double divideI(int x, int y) {
if (y == 0) {
throw Exception('Cannot divide by 0!');
}

return x / y;
}
int divideI(int x, int y) => x ~/ y; /// this will throw if y == 0
/// Error handling using [Option] 🎉
Option<double> divideF(int x, int y) {
/// Error handling without exceptions using [Option] 🎉
Option<int> divideF(int x, int y) {
if (y == 0) {
return none();
}

return some(x / y);
return some(x ~/ y);
}

/// Error handling with exceptions using [Option] 🎉
Option<int> divide2F(int x, int y) => Option.tryCatch(() => x ~/ y);

void main() {
// --- Initialize an Option 👇 --- //
const someInit = Some(10);
Expand Down

0 comments on commit 872f1b5

Please sign in to comment.