Search code examples
f#unit-type

Why would a function signature have a unit parameter following other parameters?


I am looking at a function that I saw on a training course and cannot understand the use of "()" at the end of the following function:

let acclock (start:DateTimeOffset) rate () =
    let now = DateTime.Now
    let elapsed = now - start
    start.AddTicks (elapsed.Ticks * rate)

Why would a function signature have a unit parameter at the end of other parameters on its signature?

Hence, I thought that a unit parameter meant no parameter or return type which would be similar to "void".


Solution

  • This has to do with partial application. You can bind this function to another name, providing both the start and rate parameter, creating a function of type () -> DateTime. Only when you call that function, you will execute the calculation of "elapsed = now - start" and "start.AddTicks". Like this:

    let timeThis =
        let stopClock = acclock DateTime.Now 500
        doStuff ()
        stopClock () // The function is only executed now
    

    If you would not have the () parameter at the end, you would execute that statement directly if you add the rate value.

    let acclock' (start:DateTimeOffset) rate =
        let now = DateTime.Now
        let elapsed = now - start
        start.AddTicks (elapsed.Ticks * rate)
    
    let timeThis1 =
        let stopClock = acclock' DateTime.Now
        doStuff ()
        stopClock 500 // This is only executed now
    
    // Or
    let timeThis2 =
        let stopClock = acclock' DateTime.Now 500 // Wait, we calculated it immediately
        doStuff ()
        stopClock // This is just a value