The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

EJSarge (7) [Avatar] Offline
Hi Debashish,
I frequently find I have processing I want to do both before and after something. Examples are locking accounts, beginning/committing transactions, acquiring/releasing resources.

It feels like something that might already have a name or a standard monadic way of doing it.

I thought I'd ask as I'm rather curious.

Many thanks in advance.

Debasish Ghosh (116) [Avatar] Offline
This is the classical monadic approach towards designing a sequence of actions. It's imperative in nature e.g. you want to do task1, followed by task2 and then task3 .. Typically in imperative logic you will invoke 3 functions 1 by one - in fact you can also use the template method design pattern if you want to bring some discipline in structuring the task executions.

A monadic effect is the functional way to do the same thing. That's why a monad is also often called the semicolon of functional programming. In Scala when you use the for comprehension as ..

for {
  a <- task1
  b <- task2
  c <- task3
} yield ..

you get the same effect. As an exercise de-sugar the above using map and flatMap and you will have a clear understanding of how the sequence works.

In the above case the sequence will break if one of the functions throws an exception. As an alternative effect have a look at applicatives where you execute all the functions irrespective of the output. The book discusses both the effects in detail.

EJSarge (7) [Avatar] Offline
Hi Debashish,
Thanks for the reply - I'm not sure I was clear enough about what I was asking.
for {
  a <- lockResource
  b <- doSomethingUsefulWithResource
  c <- unlockResource
} yield ..

lockResource/unlockResource should always surround doSomethingUsefulWithResource

I was wondering if there was a standard functional or monadic way to do this.

I did note that recently Mario Fusco posted about this with the Template section part of
That's a function wrapper - is that the best way?
Debasish Ghosh (116) [Avatar] Offline
You are correct. What u r talking about is the functional variant of the Template Method pattern in a monadic context.