i need to write a function which calculates how many elements on list with scheme language.
for example
(howMany 'a) returns 0
(howMany '(a b)) returns 1
(howMany '(a (b c))) returns 2
how can i do that? i did not want a working code, just only an idea for do that. so maybe you should consider to remove working codes. 🙂 thank you
The fold answers will work. However, if this is homework, you may be trying to do this using only simple built-in functions. There are two possible answers.
Here’s the naive way:
(Your implementation of Scheme may have a function
empty?instead ofnull?.)However, this algorithm will take an amount of space linearly proportional to the number of elements in the list, because it will store
(+ 1 ...)for each element of the list before doing any of the additions. Intuitively, you shouldn’t need this. Here’s a better algorithm that avoids that issue:(Bonus points: use Scheme’s
(let iter ...)syntax to write this more succinctly. I used this style because it’s more clear if you only know a few Scheme primitives.)