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

时间:2015-05-12 10:56:34

标签: 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")

这是类型:

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())

1 个答案:

答案 0 :(得分: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")

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

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

let (|LessThan|_|) k value = if value < k then Some() else None
let (|MoreThan|_|) k value = if value > k then Some() else None

然后你可以改用它们:

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")

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