typed_monad 0.0.4 copy "typed_monad: ^0.0.4" to clipboard
typed_monad: ^0.0.4 copied to clipboard

monad implementation for dart

example/typed_monad_example.dart

import 'package:typed_monad/typed_monad.dart';
import 'package:typed_monad/src/base.dart';

Future<void> main() async {
  a().unwrapOr(-1);
  a().unwrapOrElse((e) => FromException(e).type == SomeError ? 1 : -1);

  TrySync(throw1).unwrapOr(-1);
  await TryFuture(throw2).unwrapOr(-1);
  await TryFuture(() async {
    return -1;
  }).unwrapOr(-1);
  await TryFuture(throw2).unwrapOr(0);
  await TryFutures([
    throw2(),
    throw2(),
    throw2(),
  ]).unwrap;
  await TryFutures([
    throw2(),
    throw2(),
    throw2(),
  ]).unwrapOr(Future.value([1, 2, 3, 4]));
}

//monad
sealed class Errors implements Exception {}

final class SomeError implements Errors {}

Result<int, Errors> a() {
  return Err(SomeError()); //or Ok(1)
}

Option<int> b() {
  return Some(1); //or None()
}

//impl bloc
final class CounterState {
  final int value;

  CounterState(this.value);
}

sealed class CounterEvent {
  final int value;

  CounterEvent(this.value);
}

final class Increment extends CounterEvent {
  Increment(super.value);
}

final class Decrement extends CounterEvent {
  Decrement(super.value);
}

final class CounterViewModel extends ViewModel<CounterState, CounterEvent> {
  CounterViewModel() : super(Ok(CounterState(0))) {
    event.listen(
      (e) => switch (e) {
        Increment() => state.value + 1,
        Decrement() => state.value - 1
      },
    );
  }
}

int throw1() {
  try {
    throw Exception("error");
  } catch (_) {
    rethrow;
  }
}

Future<int> throw2() async {
  try {
    await Future.delayed(Duration(seconds: 1));
    throw Exception("error");
  } catch (_) {
    rethrow;
  }
}
0
likes
140
points
45
downloads

Publisher

unverified uploader

Weekly Downloads

monad implementation for dart

Repository

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

rxdart

More

Packages that depend on typed_monad