1

感谢这个伟大网站的人们,我设法将几乎完整且有效的代码放在一起。我有最后一个问题。

这是代码:

     (define (chartest ch)
       (lambda (x) (char=? x ch)))

     (define fsm-trans
        '((A (lambda (x) (string=? x "a") B), (B (lambda (x) (string=? x "a") C)))))

     (define (find-next-state state ch trl)
       (cond
         [(empty? trl) false] 
         [(and (symbol=? state (first (first trl)))
              ((second (first trl)) ch))
          (third (first trl))]
         [else (find-next-state state ch (rest trl))]))


     (define fsm-final '(C))

     (define start-state 'A)

     (define (run-fsm start trl final input)
       (cond
         [(empty? input)
          (cond
            [(member start final) true]
            [else false])]
         [else 
          (local ((define next (find-next-state start (first input) trl)))
            (cond
              [(boolean? next) false]
              [else (run-fsm next trl final (rest input))]))]))


     (run-fsm start-state fsm-trans fsm-final (string->list "ac"))

我对转换函数 find-next-state 有疑问。如何定义它以测试传入的字符,并基于此在 fsm 达到最终状态时返回真值,或者在没有达到最终状态时返回假值?

谢谢您的回答。

更新:

感谢您的回答,很抱歉代码令人困惑。我已经修复了过渡的定义,现在看起来像这样:

    (define fsm-trans
       '((A (lambda (x) (string=? x "a") B)
         (B (lambda (x) (string=? x "a") C)))))

但现在我正在尝试定义转换函数。当我没有固定的过渡字符并且我使用了字符字母时?和 char-numeric?,这些代码行就像一个魅力:

    (define (find-next-state state ch trl)
      (cond
        [(empty? trl) false] 
        [(and (symbol=? state (first (first trl)))
             ((second (first trl)) ch))
         (third (first trl))]
        [else (find-next-state state ch (rest trl))]))

但是我应该改变什么来使用 fsm-trans 中新的状态定义?在 DrScheme 中输入此代码时,会显示错误行:((second (first trl)) ch))。

感谢您的进一步协助!

4

1 回答 1

5

It looks like the main problem in this code is a confusion over quotes, quasiquotes and unquotes. Specifically, '(foo (lambda (x) x) baz) is quoting the whole thing, so there is no function there, just a symbolic representation for one. Also, your use of , looks like you're confusing it as something that separates values in a list. Another problem is that the parens look mismatched. You probably want something like this instead, using a quasiquote:

(define fsm-trans
  `((A ,(lambda (x) (string=? x "a") B))
    (B ,(lambda (x) (string=? x "a") C))))

But given that you're unclear about these things, then it'll be much better to stick to simple quotes only, and use list when needed:

(define fsm-trans
  (list (list 'A (lambda (x) (string=? x "a") B))
        (list 'B (lambda (x) (string=? x "a") C))))

You probably have some more problems to get over, but doing that should get you in the right direction.

于 2011-06-08T15:27:47.043 回答