F# less than operator in pattern matching -
for reason less operator in pattern match not work. it's error have , it's driving me insane. i'm missing obvious appreciated.
let checkaccount account = match account | {balance < 10.00} -> console.writeline("balance low") | {balance >= 10.00 , <= 100.00} -> console.writeline("balance ok") | {balance > 100.00} -> console.writeline("balance high")
this type:
type account = {accountnumber:string mutable balance:float} member this.withdraw(amnt:float) = if amnt > this.balance console.writeline("unable withdraw. amount wish withdraw greater current balance.") else this.balance <- this.balance - amnt console.writeline("you have withdrawn £" + amnt.tostring() + ". balance now: £" + this.balance.tostring()) member this.deposit(amnt:float) = this.balance <- this.balance + amnt console.writeline("£" + amnt.tostring() + " deposited. new balance is: £" + this.balance.tostring()) member this.print = console.writeline("account number: " + this.accountnumber) console.writeline("balance: £" + this.balance.tostring())
you can use pattern matching extract balance value, bind new name , compare values using when
clause:
let checkaccount account = match account | {balance = b} when b < 10.00 -> console.writeline("balance low") | {balance = b} when b >= 10.00 && b <= 100.00 -> console.writeline("balance ok") | {balance = b} when b > 100.00 -> console.writeline("balance high")
i in case, not getting using pattern matching. if wrote same code using if
, nicer.
you can use bit fancier approach , define active patterns let compare values:
let (|lessthan|_|) k value = if value < k some() else none let (|morethan|_|) k value = if value > k some() else none
then can use instead:
let checkaccount account = match account | {balance = lessthan 10.0} -> console.writeline("balance low") | {balance = lessthan 100.0 & morethan 10.0 } -> console.writeline("balance ok")
this interesting - because can use &
construct combine multiple active patterns in lessthan 100.0 & morethan 10.0
.
Comments
Post a Comment