F# Quality of Life Questions

前端 未结 3 436
死守一世寂寞
死守一世寂寞 2021-01-01 18:46

I started coding in F# about 2 months ago.

I am greatly enjoying this programming language. I come from a C# background, and every time I need to revert back to C#,

3条回答
  •  被撕碎了的回忆
    2021-01-01 19:52

    The question of improving debugging experience with F# has many aspects so it deserves a big article. So I'm afraid the question will be closed.
    Nevertheless, here are two neat tricks I'm using. I must note that I'm also a big fan of pipeline approach and so I'm facing exactly the same problems.

    Know your types.

    Having a value threaded through a chain of many transformations may quickly lead to difficulty remembering exact types at each step. The trick is:

    value
    |> transformation1
    |> fun x -> x
    |> transformation2
    

    This lets you:

    1. see the exact type of x in design time;
    2. set a breakpoint (place cursor at the function body) and see the value at debug time;
    3. Even if forgotten in the code after done, this leaves minimal footprint.

    Conditionally dump the values to console.

    Having complicated lambdas, breakpoints may be of little help. Here's yet another trick, related to the one described in @Tomas' answer: write a small function, like this:

    let inline debug x =
    #if DEBUG
        if System.Console.CapsLock then
            printfn "%A" x
            // obviously, it must not be necessarily printf;
            // it can be System.Diagnostics.Debug.WriteLine()
            // or any other logger tool that exists in the project.
    #endif
        x
    

    The usage code looks like this:

    value
    |> transformation1
    |> fun x -> x
    |> debug
    |> transformation2
    

    The idea is that:

    1. you set a breakpoint just before the debug call, just as described above;
    2. switch Caps Lock on
    3. and Step Over or just let the application run

    If you have multiple places where debug call sit, they would not spoil the output.

提交回复
热议问题