heda
heda

Reputation: 3

How to count the number of times a value appears in a list

I am trying to count how many times the name "Bob" appears in all classes.

I have these facts:

(deffacts classes
    (class 11A Peter Jack Samuel Bob Bob)
    (class 10A Lucy James John Michael Bob)
    (class 9A Bob Martin Josepth Thomas Chris Daniel)
)

The expected result is 4.

I have tried looking for a function that would count the number of occurances of a value in a list but without success.

Upvotes: -2

Views: 77

Answers (1)

Gary Riley
Gary Riley

Reputation: 10757

For individual classes:

CLIPS> 
(deffunction count$ (?v $?args)
   (bind ?count 0)
   (foreach ?a ?args
      (if (eq ?a ?v) then (bind ?count (+ ?count 1))))
   ?count)
CLIPS> 
(deffacts classes
    (class 11A Peter Jack Samuel Bob Bob)
    (class 10A Lucy James John Michael Bob)
    (class 9A Bob Martin Josepth Thomas Chris Daniel))
CLIPS> 
(defrule count
   (class ?class $?students)
   =>
   (println "Bobs in " ?class " : " (count$ Bob ?students)))
CLIPS> (reset)
CLIPS> (run)
Bobs in 9A : 1
Bobs in 10A : 1
Bobs in 11A : 2
CLIPS> 

Upvotes: 1

Related Questions