Reputation: 16841
The below F# function does not compile
open System
let checkCreation time : DateTime =
if (time > DateTime.UtcNow.AddDays(-7.0)) then printfn "New"
else printfn "Old"
checkCreation time
The error markers point to "New" and to "Old"
The compiler fails with the following error:
Script1.fsx(3,59): error FS0001: This expression was expected to have type
DateTime
but here has type
unit
Why does the compiler expect a DateTime when I'm just trying to print something via printfn?
Upvotes: 3
Views: 670
Reputation: 3476
replace this
let checkCreation time: DateTime =
with this
let checkCreation (time: DateTime) =
First one has signature (DateTime -> DateTime)
because you explicitly made this constraint to function output. Input has been inferred by compiler.
Second one has signature (DateTime -> unit)
. Input has been explicitly constrained, and output unit
inferred
Added:
Full explicit signature should look like this
let checkCreation (time: DateTime) : unit =
...
You could delete every explicit type constraint and make compiler do the work:
//because time argument compared to DateTime it is inferred to be DateTime
//No explicit constrain needed
let checkCreation time = //DateTime -> unit
//because if expression is the last one, its output will be used as function output
if (time > DateTime.UtcNow.AddDays(-7.0))
//because then branch has unit output, function output will be inferred as unit
then printfn "New"
//else branch output MUST match with then branch. Your code pass :)
else printfn "Old"
Upvotes: 6