我在第一个成员(代码的第二行)中遇到错误

时间:2019-05-13 21:16:35

标签: functional-programming f#

在第一个“成员”部分获得错误消息,

type Account = {accountNumber:string; mutable balance:float} 

    member this.Withdraw(cash:float) = 
        if cash > this.balance then
            Console.WriteLine("Insufficient Funds. The Amount you wish to withdraw is greater than your current account balance.")
        else
            this.balance <- this.balance - cash
            Console.WriteLine("You have withdrawn £" + cash.ToString() + ". Your balance is now: £" + this.balance.ToString())

    member this.Deposit(cash:float) =
        this.balance <- this.balance + cash
        Console.WriteLine("£" + cash.ToString() + " Cash Deposited. Your new Balance is: £" + this.balance.ToString())

    member this.Print = 
        Console.WriteLine("Account Number: " + this.accountNumber)
        Console.WriteLine("Balance: £" + this.balance.ToString())

程序应定义一个名为Account的f#类型,其中包含一个accountNumber(字符串)和balance(浮动)字段。该类型应包括用于将资金提取和存入帐户的方法,以及在控制台内的一行上显示字段值的打印成员。如果提款金额大于帐户余额,则应取消交易并显示适当的消息。

1 个答案:

答案 0 :(得分:4)

据我所知,代码唯一的问题是缩进-当您将成员添加到记录时,member关键字应与{对齐记录定义。

您可以通过在第一行=之后添加新行来正确定义类型:

type Account = 
    {accountNumber:string; mutable balance:float} 

    member this.Withdraw(cash:float) = 
        if cash > this.balance then
            Console.WriteLine("Insufficient Funds. The Amount you wish to withdraw is greater than your current account balance.")
        else
            this.balance <- this.balance - cash
            Console.WriteLine("You have withdrawn £" + cash.ToString() + ". Your balance is now: £" + this.balance.ToString())

    member this.Deposit(cash:float) =
        this.balance <- this.balance + cash
        Console.WriteLine("£" + cash.ToString() + " Cash Deposited. Your new Balance is: £" + this.balance.ToString())

    member this.Print() = 
        Console.WriteLine("Account Number: " + this.accountNumber)
        Console.WriteLine("Balance: £" + this.balance.ToString())

您代码中的另一个问题是Print被定义为属性而不是方法,因此我的版本还添加了()参数-这不完全是一个错误,但绝对是一个错误。将副作用操作定义为方法的良好实践。

相关问题