Skip to content

Instantly share code, notes, and snippets.

@mateusfccp
Last active February 25, 2021 17:48
Show Gist options
  • Save mateusfccp/e90e3673a80126d16aeb61f08ee1b6da to your computer and use it in GitHub Desktop.
Save mateusfccp/e90e3673a80126d16aeb61f08ee1b6da to your computer and use it in GitHub Desktop.
Writer example using Dart
import 'writer.dart';
void main() {
final initial = ' mateus é pikão!! '.writer;
// Instead of calling functions on a String, we bind them
// in our Writer<String>, building purely our log.
final result =
initial.bind(trim)
.bind(toUpperCase);
print('Result of transformations: ${result.value}');
// Only after the log has been completely and purely built
// we use them with side-effects
print('Log: ${result.log}');
}
Writer<String> toUpperCase(String s) =>
Writer(s.toUpperCase(), 'String \'$s\' was uppercased!');
Writer<String> trim(String s) => Writer(s.trim(), 'String \'$s\' was trimmed!');
import 'package:dartz/dartz.dart';
extension WriterStringExtension<T> on T {
Writer<T> get writer => Writer(this, '');
}
class Writer<T> implements MonadOps<Writer, T> {
final T value;
final String log;
Writer(this.value, this.log);
@override
Writer<T> bind<U>(Function1<T, Writer<T>> f) {
final result = f(value);
return Writer(
result.value,
'''$log
[${DateTime.now()}] ${result.log}''',
);
}
@override
Writer<B> map<B>(Function1<T, B> f) {
final result = f(value);
return Writer(result, log);
}
// TODO: Implement
@override
Writer<T> andThen<B>(covariant Writer<T> next) => throw UnimplementedError();
@override
Writer<T> ap<B>(covariant Writer<T> ff) => throw UnimplementedError();
@override
Writer<T> flatMap<B>(covariant Writer<T> Function(T a) f) =>
throw UnimplementedError();
@override
Writer<T> replace<B>(B replacement) => throw UnimplementedError();
@override
Writer<T> strengthL<B>(B b) => throw UnimplementedError();
@override
Writer<T> strengthR<B>(B b) => throw UnimplementedError();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment