gpt4 book ai didi

F#:此表达式应具有 DateTime 类型,但此处具有类型 unit

转载 作者:行者123 更新时间:2023-12-05 01:21:47 27 4
gpt4 key购买 nike

下面的 F# 函数不编译

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

checkCreation time

错误标记指向"new"和“旧”

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

Script1.fsx(3,59): error FS0001: This expression was expected to have type

DateTime    

but here has type

unit    

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

最佳答案

替换这个

let checkCreation time: DateTime = 

有了这个

let checkCreation (time: DateTime) = 

第一个有签名 (DateTime -> DateTime) 因为你明确地对函数输出做了这个约束。输入已由编译器推断。

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

添加:

完整的显式签名应该是这样的

let checkCreation (time: DateTime) : unit = 
...

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

//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"

关于F#:此表达式应具有 DateTime 类型,但此处具有类型 unit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50149863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com