F#:这个表达式应该有DateTime类型,但这里有类型单位

uri*_*rig 3 f#

下面的F#函数无法编译

open System
let checkCreation time : DateTime = 
    if (time > DateTime.UtcNow.AddDays(-7.0)) then printfn "New"
    else printfn "Old"

checkCreation time
Run Code Online (Sandbox Code Playgroud)

错误标记指向"新"和"旧"

编译器失败并出现以下错误:

Script1.fsx(3,59):错误FS0001:此表达式应具有类型

DateTime    
Run Code Online (Sandbox Code Playgroud)

但这里有类型

unit    
Run Code Online (Sandbox Code Playgroud)

当我只是想通过printfn打印一些东西时,为什么编译器会期望一个DateTime?

Sze*_*zer 6

替换这个

let checkCreation time: DateTime = 
Run Code Online (Sandbox Code Playgroud)

有了这个

let checkCreation (time: DateTime) = 
Run Code Online (Sandbox Code Playgroud)

第一个具有签名,(DateTime -> DateTime)因为您明确地将此约束设置为函数输出.输入已由编译器推断.

第二个有签名(DateTime -> unit).输入已明确约束,输出unit推断

添加:

完全显式签名应如下所示

let checkCreation (time: DateTime) : unit = 
    ...
Run Code Online (Sandbox Code Playgroud)

您可以删除每个显式类型约束并使编译器完成工作:

//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"
Run Code Online (Sandbox Code Playgroud)