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

时间:2019-05-09 21:39:01

标签: if-statement f#

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

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)

1 个答案:

答案 0 :(得分:8)

因此,让我们对代码进行一些抽象:

if a then b
elif x then y
elif p then q

由此,编译器可以告诉您,当a = true时,结果应为b。当a = false时,它应接着检查x,如果为x = true,则结果应为y。现在,如果ax都为false,则编译器知道继续进行p的检查,如果为p = true,则结果为q

但是这里的问题是:abp这三个全都为假时,结果应该是什么?

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


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

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

> printf "foo"
it : unit = ()

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

现在让我们看看如果我需要将printf呼叫放在if内会发生什么:在任何if中,thenelse分支都必须具有相同的类型,否则不清楚整个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