Reputation: 11595
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".
Upvotes: 3
Views: 293
Reputation: 490
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
Upvotes: 7
Reputation: 14896
With the additional ()
, you can pass the start
and rate
parameters and get a partially applied function unit -> DateTime
.
let partiallyAppliedAcclock = acclock DateTime.Now 1L
val partiallyAppliedAcclock : (unit -> System.DateTime)
Without the ()
, it would be a DateTime
value.
let acclockValue = acclock2 DateTime.Now 1L // acclock defined without ()
val acclockValue : DateTime = 06-12-15 3:20:41 PM
The difference is not important for pure functions (you can always replace a call to a pure function with its value), but acclock
is not pure. It uses DateTime.Now
, so every time it's called the result will be different.
Upvotes: 4