语句是可以的,直到它有错误的最终elif“预期有类型单位”为止。
type BankAcc = {AccNum:int; mutable Balance:float} with
member this.Withdraw(amount,?withdrawal) =
let withdrawAmount = this.Balance * float amount
match withdrawal with
| None -> withdrawAmount
| Some deduct -> withdrawAmount - deduct
let Account ={AccNum=123;Balance = 15.00}
Account.Withdraw(25.00) // withdrawing 25 from an account with a balance of 15
let test Balance withdrawAmount =
if Balance = withdrawAmount then "Equals"
elif Balance < withdrawAmount then "Balance too low"
else Balance - withdrawAmount
Account={AccNum =0001; Balance=0.00};
let CheckAccount Balance =
if Balance < 10.00 then "Balance is low"
elif Balance >= 10.00 && Balance <= 100.00 then "Balance is ok"
elif Balance > 100.00 then "balance is high"
let sort = Seq.unfold(fun Balance -> if(snd Balance => 50)then List.map(fun accounts-> Balance <50) list1)发布于 2019-05-09 22:45:23
因此,让我们抽象一下您的代码:
if a then b
elif x then y
elif p then q由此,编译器可以看出,当a = true时,结果应该是b。当a = false时,它应该检查x next,如果是x = true,结果应该是y。现在,如果a和x都是false,编译器知道如何检查p,如果是p = true,则结果是q。
但问题是:当a、b和p这三者都被证明是错误的时候,结果应该是什么?
您还没有告诉编译器在这种情况下应该做什么,所以它当然会抱怨!
但为什么它会如此隐晦地抱怨呢?unit和它有什么关系?
这与F#中存在的一种小的语法放松有关,以方便开发人员的生活。您知道,因为F#不是一种纯函数式语言,这意味着它可能有任意的副作用,通常这些副作用不会返回任何有意义的值,例如printf:
> printf "foo"
it : unit = ()这个函数没有什么好的返回类型,但是必须有一些返回类型,并且有一个特殊的类型只是为了这个场合- unit。它是一种特殊的类型,只有一个值,所以它并不意味着什么。
现在,让我们看看如果我需要将printf调用放入if中会发生什么:在任何if中,then和else分支都必须具有相同的类型,否则不清楚整个if表达式的类型应该是什么。因此,如果我的then分支包含一个printf,那么我的else分支也必须是unit类型的。所以我不得不把这个毫无意义的附录放在那里:
> if foo then printf "bar" else ()
it : unit = ()这真烦人。事实上,非常恼人的是,F#语言有一个特例:当我的then分支是unit类型时,我可以完全省略else分支,编译器就会假设我的意思是else ()。
> if foo then printf "bar"
it : unit = ()这就是在您的情况下所发生的事情:由于您省略了else分支,编译器假设所有then分支都必须是unit类型,但它们显然是float类型,所以编译器会抱怨。
要解决这个问题,您需要提供一个else分支。从您的代码来判断,在我看来,您确实想到了一些可能的情况:(1)少于10,(2)介于10到100之间,(3)其他所有情况。如果是这样,“所有其他”分支都应该是else。
if Balance < 10.00 then "Balance is low"
elif Balance >= 10.00 && Balance <= 100.00 then "Balance is ok"
else "balance is high"P.S.修复后,test函数中将出现类似的问题:两个then分支是string,但else分支是float
https://stackoverflow.com/questions/56067957
复制相似问题