This ia an assignment problem:
In class, we have shown you a program which mimics transactions done on a bank account. For this we have first defined a data-type for transactions:
type transaction = Withdraw of int | Deposit of int | CheckBalance | ChangePassword of string | Close
We have added two new transactions to the example done in class. In class, we defined a function make-account which generates a bank account when given an opening balance. In this exercise, you are asked to modify this code and generate a password-protected bank account. Any transaction on the bank account should only be possible, if one provides the right password. For this, implement the function makeProtectedAccount with the arguments and types shown below. let makeProtectedAccount(openingBalance: int, password: string) = This function takes in the opening balance as a first argument and the password as a second, and will return a function which when given the correct password and a transaction will perform the transaction. One crucial difference to be noted right away is that in the new code I want you to print the balance on the screen instead of returning it as a value.
I tried to declare a function in OCaml which takes as input a tuple. But it gave me an error when I tried to tell the compiler what type are each of the elements in the tuple. However, the compiler compiles when I put parenthesis around the type definition of each of the items in the tuples. Furthermore, I tried to put multiple statements as the execution sequence of a matched case in a match statement, but the compiler cannot recognize it. How can we execute multiple statements for a matched case?
function declaration with Compilor error:
makeProtectedAccount(openingBalance: int, password: string) =
function declaration without compilor error:
makeProtectedAccount((openingBalance: int), (password: string)) =
Codes that I wrote so far, as you can see the compiler dosen't understand that |Deposit is a matched case as it does not indent the statement automatically:
let makeProtectedAccount ( (openingBalance : int) , (password : string) ) =
let balance = ref openingBalance in
let pass = ref password in
fun (( passs : string ), (tras : transaction)) ->
if !passs = pass then
match trans with
| Withdraw q -> (if balance >= q then balance := !balance - q ; Printf.printf "withdrawing %d dollar, you have %d dollar left" q !balance
else Printf.printf "Invalid: withdrawing more money than you have!")
|Deposit q -> balance := !balance + q; Printf.printf "Deposit %d, you have now %d ", q !balance