这是一个分配问题:
我们在课堂上向您展示了一个模拟已完成交易的程序 在银行帐户上。为此,我们首先为 交易:
type transaction =提取int |存款int | CheckBalance |字符串的ChangePassword |关闭
我们添加了两个新的 事务以示例在课堂上完成。在课堂上,我们定义了一个 功能make-account,当给定一个 期初余额。在本练习中,要求您修改此代码 并生成一个受密码保护的银行帐户。上的任何交易 银行帐户只有在提供权利的情况下才可能存在 密码。为此,使用以下命令实现功能makeProtectedAccount 下面显示的参数和类型。让 makeProtectedAccount(openingBalance:int,密码:string)=此 函数将期初余额作为第一个参数,而 密码作为第二个密码,并将返回一个函数 正确的密码,然后交易将执行交易。一 要立即指出的关键区别是在新代码中 希望您在屏幕上打印余额而不是将余额返回为 一个值。
我试图在OCaml中声明一个以元组为输入的函数。但是,当我尝试告诉编译器元组中的每个元素是什么类型时,它给了我一个错误。但是,当我在元组中每个项目的类型定义周围加上括号时,编译器会进行编译。此外,我试图将多个语句作为匹配大小写的执行顺序放在match语句中,但是编译器无法识别它。如何为匹配的案例执行多个语句?
带有编译器错误的函数声明:
makeProtectedAccount(openingBalance: int, password: string) =
没有编译器错误的函数声明:
makeProtectedAccount((openingBalance: int), (password: string)) =
到目前为止,我看到的代码可以看到编译器无法理解| Deposit是匹配的情况,因为它不会自动缩进语句:
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
答案 0 :(得分:2)
这里有多个问题
与您一样,或者
let makeProtectedAccount ((openingBalance, password): int*string) =
match
情况下编写多个语句也一样
match trans with
| Withdraw q -> Printf.printf "statement 1\n"; Printf.printf "statement 2\n"
| Deposit q -> Printf.printf "statement 3\n"; Printf.printf "statement 4\n"
我认为问题是您上一个,
的流浪printf
。另外,passs
不是ref
,不需要用!
取消引用。另外,在then
分支
这应该可以工作
let makeProtectedAccount ((openingBalance:int), (password:string)) =
let balance = ref openingBalance in
let pass = ref password in
function
| p, Withdraw q when p = !pass ->
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!"
| p, Deposit q when p = !pass -> balance := !balance + q; Printf.printf "Deposit %d, you have now %d " q !balance
| _, _ -> ()
顺便说一句,如果没有特别的理由接受一个元组,那么写带有两个参数的function
会更加习惯化
let makeProtectedAccount (openingBalance:int) (password:string) =