Skip to content

Instantly share code, notes, and snippets.

@srdjan
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srdjan/58d17cdb05276ab6b259 to your computer and use it in GitHub Desktop.
Save srdjan/58d17cdb05276ab6b259 to your computer and use it in GitHub Desktop.
//-- monad interface
//--
public interface IMonad<T> {
//IMonad<T> From(T @value);//note: implemented as constructor
IMonad<T2> Bind<T2>(Func<T, T2> f) where T2 : class;
// simple access the wrapped value(s), optional but helpfull :)
string Show();
}
//-- Maybe monad
//--
class MaybeM<T> : IMonad<T> {
internal T _value;
public MaybeM(T value) {
_value = value;
}
public IMonad<T2> Bind<T2>(Func<T, T2> f) where T2 : class {
if (_value != null) {
return new MaybeM<T2>(f(_value));
}
return new MaybeM<T2>(null);
}
public string Show() {
return _value == null ? "null" : _value.ToString();
}
}
//-- Writer monad
//--
class WriterM<T> : IMonad<T> {
internal T _value;
List<string> _info;
public WriterM(T @value) {
_value = value;
_info = new List<string>();
}
WriterM(T @value, List<string> info) {
_value = @value;
_info = info;
}
public IMonad<T2> Bind<T2>(Func<T, T2> f) where T2 : class {
try {
var result = (f(_value));
_info.Add("\{(f.Method).Name}()-> \{result}");
return new WriterM<T2>(f(_value), _info);
}
catch (Exception ex) {
_info.Add("Exception: \{ex.Message} thrown for \{(f.Method).Name}()");
return new WriterM<T2>(default(T2), _info);
}
}
public string Show() {
var valStr = _value.ToString();
_info.ForEach(s => valStr += "\r\n\t" + s);
return valStr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment