0

I'm trying to find the first missing key in a hash table, that should contain keys [1 ... N], using Scheme.

So far, I have the following code:

(define (find-missing n ht)
  (define c 1)

  (let forVertices ()
    (cond (not (hash-has-key? ht c))
      (c)
    )

    (set! c (+ c 1))
    (when (>= n c) (forVertices))
  )
)

When I execute the function to test it, nothing is returned. What am I doing wrong?

4

1 回答 1

2

括号有几个问题,并且else案例丢失了。这应该可以解决错误:

(define (find-missing n ht)
  (define c 1)
  (let forVertices ()
    (cond ((not (hash-has-key? ht c))
           c)
          (else
           (set! c (+ c 1))
           (when (>= n c)
             (forVertices))))))

……但是您应该知道,您编写程序的方式根本不是惯用的。一般来说,在Scheme中你应该避免改变状态(set!操作),你可以通过正确设置递归和传递正确的参数来编写一个等效的过程。此外,最好在递归退出时返回一些东西(例如:) ,否则如果没有缺少键#f,您的过程将返回。#<void>在这里,这就是我的意思:

(define (find-missing n ht)
  (let forVertices ((c 1))
    (cond ((> c n) #f)
          ((not (hash-has-key? ht c)) c)
          (else (forVertices (+ c 1))))))
于 2013-11-07T03:24:23.420 回答