0 Replies - 1799 Views - Last Post: 06 July 2011 - 08:58 PM

#1 I X Code X 1   User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 66
  • Joined: 28-July 10

[Lisp] Finding the amount of a specific element in a list

Posted 06 July 2011 - 08:58 PM

Description: Will work in any ANSI Lisp Implementation; I used Allegro Common Lisp Express EditionFinds the amount of a specific element in a list; without using the built in 'count' function.
;; Common Lisp has a 'count' function that returns the amount of elements
;; in a list. Using that might be the quick and easy way out, but it does
;; not teach you anything.

; So here's a function that does the same thing:

(defun my-count (x list)
              (length (loop for m in list if (equal x m) collect m)))

;; my-count takes a symbol and a list as parameters. We use four very
;; important things here: length, loop, if and collect

; length: will return the length of any sequence (list, vector, array, etc)

; loop: loop is a macro; not a function. It differs from a function in that
; it has it's own "mini-language" that is used differently than what 
; Common Lisp does. "Functions", which are themselves macros, do not need
; to be inside parentheses, unless you use 'do'. 'do' means that from this
; point on in the code only lisp-expressions will be used: the parens!

; if: if is one of these macros. Notice how we do not place it inside a 
; parentheses. If 'do' was before this we would need to use parentheses.

; collect: collects the individual elements of a list that meet our 
; criteria.

; Output:

CG-USER(12): (my-count 'a '(a a a b a))

Is This A Good Question/Topic? 0
  • +

Page 1 of 1