简体   繁体   English

创建球拍错误消息

[英]Creating a Racket error message

I'm having a very hard time creating what should be a simple error message for a recursive function. 我很难为递归函数创建简单的错误消息。 I have this program: 我有这个程序:

(check-expect (rewrite '(x x x - x x x x) 3 'x)
       (list 'x 'x 'x 'x 'x 'x 'x 'x))
(check-error (rewrite '(5 4 3 2 1) 5 6) 
         "rewrite: 5 is too large for (5 4 3 2 1)")

(define (rewrite init-ls init-n init-val)
  (local [(define (help ls n val)
            (cond 
              [(zero? n) (cons val (rest ls))]
              [(empty? ls) (error 'rewrite 
                                       (format "~s is too large for ~s"
                                                init-n init-ls))]      
              [else (cons (first ls) 
                          (rewrite (rest ls) (sub1 n) val))]))]
        (help init-ls init-n init-val) ))

Basically it just replaces the element at position n of a list with the val (value) you choose. 基本上,它只是将列表中位置n的元素替换为您选择的val(值)。 I can't get the error message to work at all though for when n is greater than the length of the list. 虽然当n大于列表的长度时,我根本无法获得该错误消息。

*I do not want to use (length list) because obviously that would be very slow when you start putting a large numbers of items in a list *我不想使用(长度列表),因为当您开始在列表中放置大量项目时,这显然很慢

I've tried using no local function, putting it above the (zero?), and outside the local function multiple ways but just can't get it to work. 我试过不使用任何局部函数,将其置于(零?)之上,并在局部函数之外进行多种方式,但无法使其正常工作。 Any help would be great in ISL+ ISL +方面的任何帮助都将非常有用

There are two small issues here. 这里有两个小问题。 The first is that the clauses to check for zero? 首先是要检查zero?的子句zero? and empty? empty? should be reversed, since the zero? 应该zero? ,既然zero? case assumes a non-empty list. case假定为非空列表。

The more important issue is probably just a typo. 更重要的问题可能只是拼写错误。 When you recur, you call rewrite itself, not help : 重复出现时,您调用自身rewrite ,而不是help

[else (cons (first ls) 
            (rewrite (rest ls) (sub1 n) val))]

You should be calling help instead, which will preserve the values of init-ls and init-n for use in your error message. 您应该改为调用help ,它将保留init-lsinit-n的值以用于错误消息。

The fixed code looks like this: 固定代码如下所示:

(define (rewrite init-ls init-n init-val)
  (local [(define (help ls n val)
            (cond
              [(empty? ls) (error 'rewrite
                                  (format "~s is too large for ~s"
                                          init-n init-ls))]
              [(zero? n) (cons val (rest ls))]
              [else (cons (first ls)
                          (help (rest ls) (sub1 n) val))]))]
    (help init-ls init-n init-val)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM