TypeError,该对象不适用 [英] TypeError, the object is not applicable

查看:138
本文介绍了TypeError,该对象不适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个相对简单的银行帐户功能,但是当我尝试运行它时,出现TypeError,我不确定为什么吗?它与SICP完全不同,因此该解决方案随时可用,我只想了解为什么我的答案会产生该错误.有什么想法吗?这是我的代码:

I wrote a relatively simple bank account function, however when I try to run it I get an TypeError and I'm not sure to why? It's straight out of SICP so the solution is readily available, I just want to understand why my answer produces that error. Any thoughts? Here is my code:

(define (make-password-account balance password)
    (define (withdraw amount)
        (if (>= balance amount)
            (begin (set! balance (- balance amount))
                balance)
            "Insufficient Funds"))
    (define (deposit amount)
        (set! balance (+ balance amount))
        balance)
    (define (dispatch users-guess-at-password m)
            (if (eq? users-guess-at-password password)
                (cond   ((eq? m 'withdraw) withdraw)
                        ((eq? m 'deposit) deposit)
                        (else (error "Unknown Request --make-account" m)))
               "INVALID PASSWORD"))
dispatch)

以下是口译员的相关口译员输入和输出:

Here is the relevant interpreter inputs and outputs from the interpreter:

..loaded function...
>(define acc (make-password-account 100 'secret))
acc
>((acc 's 'withdraw) 2)
;Stack Trace:  
0  TypeError: The object "Invalid Password" is not applicable.  
1  ((acc (quote s) (quote withdraw) 2)

推荐答案

当前您的代码正在执行此操作:

Currently your code is doing this:

((acc 's 'withdraw) 2)
((dispatch 's 'withdraw) 2)
("INVALID PASSWORD" 2)
=> TypeError: The object "INVALID PASSWORD" is not applicable.

您必须处理输入密码错误的情况.因为如果密码不正确,您将无法对帐户做任何有用的事情,因此应发出错误并停止执行,例如替换此行:

You have to handle the case where the password entered is wrong. Because you can't do anything useful with the account if the password is incorrect, you should signal an error and stop execution, for instance replacing this line:

"INVALID PASSWORD"

与此:

(error "INVALID PASSWORD")

现在,该过程将返回有意义的错误消息并停止执行.或者,如果发信号通知错误太过激烈,则可以返回一个字符串,如@molbdnilo所建议.再次将"INVALID PASSWORD"替换为建议的过程,无论它作为参数收到什么,都将返回错误字符串:

Now the procedure will return a meaningful error message and stop execution. Alternatively, if signaling an error is too drastic, you could return a string, as suggested by @molbdnilo . Once again replace "INVALID PASSWORD" for the suggested procedure, which no matter what it receives as parameter will return the error string:

(lambda (x) "INVALID PASSWORD")

现在执行将如下所示:

((acc 's 'withdraw) 2)
((dispatch 's 'withdraw) 2)
((lambda (x) "INVALID PASSWORD") 2)
=> "INVALID PASSWORD"

这篇关于TypeError,该对象不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆