Skip to content

Instantly share code, notes, and snippets.

@srdjan

srdjan/maybeM.cs

Last active Aug 29, 2015
Embed
What would you like to do?
//-- 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
You can’t perform that action at this time.