Ask HN: How would you do this in Haskell?
Say I have a complicated calculation, but it's pure functional all the way. Now somewhere in the middle of it, I want to log something if some condition is met. In a procedural language, that's easy - I just add an "if" and a log statement. But how would you do that in Haskell?
The best answer I've come up with so far is, from that function, to return a tuple containing two values: the value the function returned before, and a Maybe. The Maybe contains Just String if the logging happened, and Nothing otherwise.
But then all functions from there to the end of the calculation have to be changed to return a tuple instead of just the results of the calculation. That doesn't sound like composablility.
Or, I could jam IO into the function where the data was to decide whether to do the logging, but that just feels wrong.
What's the idiomatic way to do something like this?
(
11 comments
| 7 points
| on HN
)
If that sounds helpful, see: http://praisecurseandrecurse.blogspot.com/2013/07/the-polar-... and see also the next post in the blog. Then maybe go from there!
It's just a fancy name for composing functions of the form `a -> (b, String)`, via
But doesn't using that involve making the rest of the code (at least from the function that needs to log out to the top level) return monads, rather than returning whatever they were returning before?
1. Explicitly end the scope of implicitly logging things by calling runWriter, and getting a pair of (result, log) out.
2. Continue working in the implicit log monad, which would mostly involve extracting the result of the log function with `do x <- theLoggingThing`, but you can still mix in pure statments with `do let y = 5` or other function calls, and then end the do block with `return val`, where val was what you were going to return before.
Now, perhaps you could argue that the right way to do the problem (without the logging) in Haskell is to not have functions like that - to break up that function so that the data that, in my version, is only available within the function is instead explicitly returned by some smaller function.
But if you don't argue that, then you're left with the stated problem: What's the right way of getting logging out of the middle of a function in Haskell?