Being ill sucks

Last week I was really very ill – something flu-like – and this week I’m slowly recovering from whatever it was. Beside sapping all of my energy it’s also completely messed with my ability to actually think. Because of that, I haven’t really done anything particularly interesting – I’ve been using this time to do all of the boring / monotonous tasks that I’d been putting off – and haven’t had any particularly exciting insights into, well, anything really.

Never too ill for a monad

Since I’ve not really done much, and I’m not feeling up to writing about anything particularly involved, here’s a very simple error monad-like-structure I threw together this week for something I was working on.

public class Exceptional<TValue>
	#region Fields

	private readonly TValue value;
	private readonly Exception exception;
	private readonly bool hasResult;


	#region Constructors

	private Exceptional(TValue value)
		this.value = value;
		hasResult = true;

	private Exceptional(Exception exception)
		this.exception = exception;
		hasResult = false;

	#region Methods

	public Exceptional<T> Apply<T>(Func<TValue, T> func)
		return UnWrap(
			v => Exceptional<T>.Wrap(() => func(v)),
			ex => new Exceptional<T>(ex));

	public T UnWrap<T>(
		Func<TValue, T> whenResult,
		Func<Exception, T> whenException)
		return hasResult
			? whenResult(value)
			: whenException(exception);

	public static Exceptional<TValue> Wrap(Func<TValue> func)
			return new Exceptional<TValue>(func());
		catch (Exception exception)
			return new Exceptional<TValue>(exception);


The brain is a muscle…

So, even though I really wasn’t feeling particularly up to it, I wrote something similar to the above in F#. I’m trying to slowly get a feel for the language after years of OOP indoctrination, and this is (sadly) probably the biggest thing I’ve written in F# so far. I love the concepts behind the language but it can be incredibly frustrating to move from being able to produce clean, concise, idiomatic code in C# to struggling to write even the simplest structures in F#.

type Exceptional<'a> = 
	| Value of 'a
	| Ex of Exception

// (a -> b) -> (a -> Exceptional<b>)
let Bind f = 
	fun a -> 
		try Value(f a) 
			| ex -> Ex(ex)

let incr x = 
	match x with 
		| 7 -> 	raise (Exception "Seven Eight Nine")
		| _ -> 	x + 1
let _incr =  Bind incr

_incr 3 |> Console.WriteLine
_incr 7 |> Console.WriteLine

Leave a Reply

Your email address will not be published. Required fields are marked *