Generate random sentence from grammar

Code which generates a random sentence using a specific grammar. The code shows example of reducer function and tranducers.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(def grammar {:sentence [[:noun-phrase :verb-phrase]]
:noun-phrase [[:article :noun]]
:verb-phrase [[:verb :noun-phrase]]
:article ["the" "a"]
:noun ["ball" "car" "man" "woman" "dog" "table" "bed"]
:verb ["hits" "stole" "saw" "licked" "bites"]})

(declare process-rule)

(defn process-keyword-element [rule]
(cond
(keyword? rule) (process-rule (rand-nth (get grammar rule)))
:else rule))

(def process-keyword-elements
(map process-keyword-element))

(defn process-rule-vector [rule]
(cond
(vector? rule) (sequence (comp process-elements ucase-elements) rule)
; (vector? rule) (map process-keyword-element rule)
:else rule))

(defn build-str
([] nil)
([a] a)
([a b] (if a (str a " " b) b)))

(defn make-sentence []
(reduce build-str
(flatten (process-rule-vector [:sentence]))))

 

Leave a Reply

Your email address will not be published. Required fields are marked *