Something like a yield gap in F #

How to break first if?

let WithdrawalCash (account, amount) = seq { if ( account.Balance.CurrentAmount - amount < 0.0m) then yield NotEnoughMoneyForWithdrawal(account, amount) // How to break here? let newBalance = account.Balance.CurrentAmount - amount yield CashWithdrawnEvent(account, newBalance) } 
+4
source share
2 answers

Not sure if this helps, why not use an else clause?

 let WithdrawalCash (account, amount) = seq { if ( account.Balance.CurrentAmount - amount < 0.0m) then yield NotEnoughMoneyForWithdrawal(account, amount) // How to break here? else let newBalance = account.Balance.CurrentAmount - amount yield CashWithdrawnEvent(account, newBalance) } 

Also see:

hubsFs - Break in F #?

Imperative Computation in F # (II.) - Writing an Interrupt and Continuing

hubsFs - break: outdated or not yet implemented?

+6
source

The code above will only ever return one CashWithdrawlEvent, and then end the sequence ... you need the loop to return multiple values. Also, have you considered using match to handle multiple cases?

(not tested as working)

 let WithdrawalCash (account, amount) = seq { let bDone = ref false while not (!bDone) do match amount with | v when account.Balance.CurrentAmount - v < 0 -> yield NotEnoughMoneyForWithdrawal(account, amount) bDone := true // break // more when clauses can go here | _ -> let newBalance = account.Balance.CurrentAmount - amount yield CashWithdrawnEvent(account, newBalance) // let the sequence continue } 

But even this does not look like what you would like, since it will ALWAYS output the same โ€œamountโ€ every time you pull the value out of the sequence, because the account and the amount are fixed when creating the sequence. So, I would reset "seq" and make this simple function, as in:

 let WithdrawalCash (account, amount) = match amount with | v when account.Balance.CurrentAmount - v < 0 -> NotEnoughMoneyForWithdrawal(account, amount) // more when clauses can go here | _ -> let newBalance = account.Balance.CurrentAmount - amount CashWithdrawnEvent(account, newBalance) 

In the general case of listing a sequence and stopping when a specific condition is satisfied, consider "Seq.takeWhile", as in:

 let MySeq = seq { while true do yield someValue } let code () = MySeq |> Seq.takeWhile ( fun v -> ShouldIContinueWorkingTest(v) ) |> Seq.iter ( fun v -> DoWork(v) ) 
+2
source

All Articles