Search code examples
functionlispcontrol-flow

Recursion in Lisp and making my own length function


I am trying to make my own length/2 function(which allows you to find the length of a list) in lisp and am having an issue.

If I were to program this in java I would create a global index variable

that = 0

Then in the method I would do

if(list.equal(null))
{
    return index;
}
else
{
    index++;
    return functioname(tail of list) ;
}. 

Obviously this is not actual java syntax but I am just trying to relay the logic I want to apply in lisp.

My main issue is that ifs in lisp only allow you to do

if test expression
    then do something
else
    do something else

while I am trying to do

if test expression
    then do something
else
    do 2x something

Is there a way I can accomplish this in lisp or is there a better way to go about this problem?


Solution

  • Do it recursively:

    len(list):
        if list is null
            return 0
        else
            remove first_item from list
            return 1 + len(list)
    
    
    (define (length items)
      (if (null? items)
          0
          (+ 1
             (length (cdr items)))))
    
    
    (length (list 1 2 3))
    

    3

    Or use set!:

    (define count 0)
    
    (define (length items)
      (when (not (null? items))
        (set! count (+ count 1))
        (length (cdr items))))
    
    (length (list 1 2 3 4 5))
    
    count
    

    5