1

这些天我参加了 Peter Norvig 的 Udacity 课程 CS212:计算机程序设计。不幸的是,这门课程都是用 Python 编写的,所以为了学习,我在 Racket 中为该课程的第 3 单元中给出的正则表达式编译器编写了等效代码。

你可以在这里看到我的代码:http: //codepad.org/8x0rMXOi

现在,困扰我的是 Norvig 先生的 Python 原始代码比我的要短一些。:( 但是好吧,我只是 Racket 的初学者,这是意料之中的。但我想知道是否有一些 Racket 专家可以缩短我的代码,使 Racket 代码变得比原始 Norvig 的 Python 代码更短?

4

1 回答 1

3

这里有一些提示。

ormap 表达式在:

 (define (in-chars? c chars)
   (ormap (lambda (ch) (equal? c ch)) (string->list chars))) 

可以写成

   (memv c (string->list chars)) 

中的 if-epression

(define (match pattern text)
  (define remainders (pattern text))
  (if (not (set-empty? remainders))
      (substring text 0 (- (string-length text)
                           (string-length (argmin string-length 
                                                  (set->list remainders)))))
      #f))

可以写成

 (and (not (set-empty? remainders))
      (substring ...)

但是你的功能很小而且很重要,所以我不会改变太多。

操作字符串的更方便的语法将使字符串操作程序的读写更容易。几年前我做了一个尝试,写了一个 concat 宏。

我用它来实现 Norvig 的拼写检查器(你可能会对他的原始文章感兴趣)。生成的拼写检查器和 concat 宏在此处解释

http://blog.scheme.dk/2007/04/writing-spelling-corrector-in-plt.html

更新:我编写了拼写检查器的更新版本。concat 宏使简单的字符串操作更短。

https://github.com/soegaard/this-and-that/blob/master/spell-checker.rkt

于 2012-05-04T13:38:25.900 回答