F#If语句期望浮点数的单位

Sam*_*rry 2 f# if-statement

该语句是正确的,直到最后一个省略号,然后出现错误“预期具有类型单位”

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

Fyo*_*kin 8

因此,让我们抽象一下您的代码:

if a then b
elif x then y
elif p then q
Run Code Online (Sandbox Code Playgroud)

据此,编译器可以告诉您when a = true,结果应为b。什么时候a = false,它应该检查x下一个,如果是x = true,结果应该是y。现在,如果两者ax变成是false,编译器知道要继续检查p,如果p = true,那么结果是q

但这里有一个问题:应该的结果是什么,当所有三个abp转出是假的?

您没有告诉编译器在这种情况下该怎么做,所以它当然会抱怨!


但是为什么它如此神秘地抱怨呢?是什么unit有什么关系呢?

这与F#中存在的小句法松弛有关,以减轻开发人员的生活。您会看到,由于F#不是函数式语言,这意味着它可以具有任意副作用,因此,这些副作用通常不会返回任何有意义的值,printf例如:

> printf "foo"
it : unit = ()
Run Code Online (Sandbox Code Playgroud)

该函数没有什么好返回的,但是必须有某种返回类型,并且有一个特殊的类型专门用于- unit。这是一种特殊的类型,仅具有一个值,因此没有任何意义。

现在让我们看看如果我需要将printf调用放在if:内的任何情况下if,会发生什么,并且thenelse分支必须具有相同的类型,否则不清楚整个if表达式应该是什么类型。因此,如果我的then分支包含a printf,则else分支也必须是type unit。所以我不得不总是把这个毫无意义的附录放在这里:

> if foo then printf "bar" else ()
it : unit = ()
Run Code Online (Sandbox Code Playgroud)

真烦人 实际上,令人烦恼的是F#语言有一个特殊情况:当我的then分支是type时unit,我可以else完全省略该分支,而编译器将仅假定我的意思是else ()

> if foo then printf "bar"
it : unit = ()
Run Code Online (Sandbox Code Playgroud)

所以这就是您的情况:由于您省略了else分支,因此编译器假定所有then分支都必须是type unit,但显然它们都是type 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"
Run Code Online (Sandbox Code Playgroud)

PS修复此问题后,您将在test函数中遇到类似问题:两个then分支为string,但else分支为float