作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面的 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/
我是一名优秀的程序员,十分优秀!