Click to See Complete Forum and Search --> : Lisp question


jutah
02-21-2001, 12:59 AM
I am new to lisp and still trying to get a hang of this new type of programming style. What I want to do is go through a list and count how many of a certain element appears in that list. For example if I had the list L '(1 4 5 1 7 8) and I want to know the amount of ones in the list it would give me 2. I can't figure out how to keep a counter going or how to handle the list if it had sub list?

thanks
jutah

Grunhund
02-21-2001, 11:20 PM
A recursive approach solves both your problems. Try an algorithm such as follows:

stop condition: There is only one element in the list
case 1: it is a match so return 1
case 2: it is not a match so return 0
case 3: it is a list so we call our funtion on this list
main algorithm:
1) check for stop condition
2) call our function passing the first element in the list
3) call our function with the remainder of the list
4) add the results from step 2 and 3

Ultimatly you will call this function on all elements of your list. Each one that matches will return 1. Adding all these 1's up results in the number of occurences in the list and all sublists.

If you want some ugly code, I'll be happy to provide some.

jutah
02-21-2001, 11:46 PM
I am starting to get it! I can get it to work on a simple list. Sub list are still a problem? Ideas??

thanks
jutah

Grunhund
02-22-2001, 12:49 AM
The way I would do it would be to check to see if an element in the list is a list before checking to see if it matches.
You can use the listp function to see if something is a list. If it is a list, just call your function on that list and it will return the number of matches in that sublist.

...
(if (listp element) (my_function element)
(if (eq matchvalue element) 1 0))
...