27

I'm new to funcctional programming and have some questions regarding coding style and debugging.

I'm under the impression that one should avoid storing results from funcction calls in a temp variable and then return that variable

e.g.

let someFunc foo =
    let result = match foo with
                 | x -> ...
                 | y -> ...
    result 

And instead do it like this (I might be way off?):

let someFunc foo =
    match foo with
    | x -> ...
    | y -> ...

Which works fine from a functionallity perspective, but it makes it way harder to debug. I have no way to examine the result if the right hand side of -> does some funky stuff.

So how should I deal with this kind of scenarios?

4 Answers 4

26

To inspect the middle of a pipeline, I suggest the following workaround:

Put this code at some place:

[<AutoOpen>]
module AutoOpenModule

#if DEBUG
let (|>) value func =
  let result = func value
  result
#endif

Enable "Step Into Properties and Operators in Managed Code":

https://msdn.microsoft.com/en-us/library/cc667388(v=vs.100).aspx

Now you should be able to step into the pipeline operator.

1
  • Completely brilliant. This is now a cherished addition to our codebase.
    – Kit
    Sep 13, 2012 at 12:31
11

Either way is acceptable, as you are simply binding to local immutable variable.

There is a catch though. If you using it as part of a recursive loop using tail calls, the one using the temp variable will eliminate the tail call, and hence you will have an increase in stack space.

1
8

Being able to see the return value of a function in VS is a long-standing request. Other intermediate expression values too; in F# for example, you often want to inspect the middle of a pipeline, which is hard to do. In the sense that functional programming means "fewer named variables and locals" and "larger expressions", this does have a negative impact on the current generation of debuggers. (On the other hand, with things like less mutability and higher abstraction, hopefully you spend less time in the debugger.)

There are still many ways the debuggers of the future can be improved...

See also

Do some Functional programming constructs reduce Debuggability?

4

I wouldn't shoot you if you used the temp, but I also wouldn't cramp my style on the off chance that I needed to watch something under debug.

Besides, debugging this sort of thing is much easier with Visual Studio 2010's visual debugger, as you can use breakpoints inside each possible match expression. There is also quick watch and other great features.

For a list of the latest features in the Visual Studio debugger: http://msdn.microsoft.com/en-us/library/01xdt7cs.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.