Tuesday, January 25, 2011

tail refactoring

I found myself with this function which I didn't like:

let seq2 p1 p2 f =
state {
let! v1 = p1
let! v2 = p2
return! f v1 v2
}

This function is meant to sequence two state monadic functions and then do something monadic with the result.

Noting that f was the last operation applied, I refactored is as:

let seq2 p1 p2 =
state {
let! v1 = p1
let! v2 = p2
return (v1, v2)
}

and I added a new operator |>@ which applies a unary monadic operator to the result of the left hand monadic operation. As seq2 is monadic I can write: seq2 x y |>@ f . The advantage is that seq2 is now more general as I have other operators like |>@.

This refactoring is about generalizing the last operation of a function.

No comments: