gpt4 book ai didi

F#:警告 FS0020:此表达式的类型应为 'unit',但类型为 'bool'

转载 作者:行者123 更新时间:2023-12-01 06:30:51 27 4
gpt4 key购买 nike

我正在尝试通过解决一些 Euler 问题来学习 F#,但我发现了一个我无法弄清楚的问题。这是我幼稚的解决方案。

let compute =
let mutable f = false
let mutable nr = 0
while f = false do
nr <- nr + 20
f = checkMod nr
nr

当我这样做时,我收到错误消息警告 FS0020:此表达式的类型应为“unit”,但在表达式“nr <- nr +20”上的类型为“bool”。我试过重写和移动表达式,但我总是在 while 语句下方的行中得到该错误。

我是用 VS2010 Beta 写的。

最佳答案

因为我可以想象这个网页成为查找有关 信息的“规范”位置。警告 FS0020 ,这是我对您收到警告的三种最常见情况以及如何解决它们的快速总结。

故意丢弃仅因其副作用而调用的函数的结果:

// you are calling a function for its side-effects, intend to ignore result    
let Example1Orig() =
let sb = new System.Text.StringBuilder()
sb.Append("hi") // warning FS0020
sb.Append(" there") // warning FS0020
sb.ToString()

let Example1Fixed() =
let sb = new System.Text.StringBuilder()
sb.Append("hi") |> ignore
sb.Append(" there") |> ignore
sb.ToString()

警告很有用,指出错误(函数无效):
// the warning is telling you useful info 
// (e.g. function does not have an effect, rather returns a value)
let Example2Orig() =
let l = [1;2;3]
List.map (fun x -> x * 2) l // warning FS0020
printfn "doubled list is %A" l

let Example2Fixed() =
let l = [1;2;3]
let result = List.map (fun x -> x * 2) l
printfn "doubled list is %A" result

混淆赋值运算符和相等比较运算符:
// '=' versus '<-'
let Example3Orig() =
let mutable x = 3
x = x + 1 // warning FS0020
printfn "%d" x

let Example3Fixed() =
let mutable x = 3
x <- x + 1
printfn "%d" x

关于F#:警告 FS0020:此表达式的类型应为 'unit',但类型为 'bool',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1108865/

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