F#小于模式匹配中的运算符

Jac*_*cob 3 f# pattern-matching

由于某种原因,此模式匹配中的小于运算符将不起作用.这是我唯一的错误,它让我疯狂.我可能错过了一些非常明显的东西,但感谢所有的帮助.

let CheckAccount account = 
match account with
| {Balance < 10.00} -> Console.WriteLine("Balance is Low")
| {Balance >= 10.00 and <= 100.00} -> Console.WriteLine("Balance is OK")
| {Balance > 100.00} -> Console.WriteLine("Balance is High")
Run Code Online (Sandbox Code Playgroud)

这是类型:

type Account = {AccountNumber:string 
            mutable Balance:float} 
            member this.Withdraw(amnt:float) = 
                if amnt > this.Balance then
                    Console.WriteLine("Unable to withdraw. The Amount you wish to withdraw is greater than your current balance.")
                else
                    this.Balance <- this.Balance - amnt
                    Console.WriteLine("You have withdrawn £" + amnt.ToString() + ". Your balance is now: £" + this.Balance.ToString())
            member this.Deposit(amnt:float) =
                this.Balance <- this.Balance + amnt
                Console.WriteLine("£" + amnt.ToString() + " Deposited. Your new Balance is: £" + this.Balance.ToString())
            member this.Print = 
                Console.WriteLine("Account Number: " + this.AccountNumber)
                Console.WriteLine("Balance: £" + this.Balance.ToString())
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 8

您可以使用模式匹配来提取余额值,将其绑定到新名称,然后使用以下when子句比较值:

let CheckAccount account = 
  match account with
  | {Balance = b} when b < 10.00 -> Console.WriteLine("Balance is Low")
  | {Balance = b} when b >= 10.00 && b <= 100.00 -> Console.WriteLine("Balance is OK")
  | {Balance = b} when b > 100.00 -> Console.WriteLine("Balance is High")
Run Code Online (Sandbox Code Playgroud)

我想说在这种情况下,你实际上并没有从使用模式匹配中获得太多.如果您使用相同的代码编写if,那么它可能看起来更好.

您可以使用更有趣的方法并定义可用于比较值的活动模式:

let (|LessThan|_|) k value = if value < k then Some() else None
let (|MoreThan|_|) k value = if value > k then Some() else None
Run Code Online (Sandbox Code Playgroud)

然后你可以改用它们:

let CheckAccount account = 
  match account with
  | {Balance = LessThan 10.0} -> Console.WriteLine("Balance is Low")
  | {Balance = LessThan 100.0 & MoreThan 10.0 } -> Console.WriteLine("Balance is OK")
Run Code Online (Sandbox Code Playgroud)

这实际上非常有趣 - 因为您可以使用该&构造来组合多个活动模式LessThan 100.0 & MoreThan 10.0.

  • 我在写这个答案的过程中分心了 :-) 又添加了一件带有活动模式的东西! (2认同)