(define( app list1 list2)
(if(empty? list1) list2
(cons (car list1) (app(cdr list1)list2))))
(app ((list "↔" "→" "∧" "⊕" "∨" "¬")) (list "P" "Q" "R" "S" "U" "X" "Y" "Z"))
(define L (list "↔" "→" "∧" "⊕" "∨" "¬"))
(define ( f L n)
(if (= n 0) "p"
(string-append "p" (car L) (f(cdr L) (- n 1)))))
(f L 3)
您有以下递归定义的提议:
编写一个DrRacket程序,该程序将随机生成具有给定操作数的命题。
我无法完成此功能。你能帮帮我吗?
答案 0 :(得分:3)
由于这是一个家庭作业问题,我将使用另一个例子向您展示技术。下面的语法有两个非终端S和T.对于每个非终端,我已经定义了一个根据规则生成随机字符串的函数。由于S有四条规则,我随机选择其中一条规则。
#lang racket
;;; Grammar
; The grammar has two non-terminals S and T.
; There are four rules for S and one for T.
; S -> aSa
; S -> bSb
; S -> cT
; S -> ε
; T -> dS
(define (S)
(case (random 4) ; random number 0,1,2,3 (four rules for S)
[(0) (string-append "a" (S) "a")]
[(1) (string-append "b" (S) "b")]
[(2) (string-append "c" (T))]
[(3) ""]))
(define (T)
; only one rule, so no need for random here
(string-append "d" (S)))
; generate a random string according to the grammar
(S)
一些示例输出:
"bb"
"bbcdbcdbbb"
"cdbb"