Exiting from a recursive call in a functional language

Viewed 21

I am currently learning racket and am having a hard time understanding how to program in a functional language. I am trying to have the function first-item match the first element of my list to either a number or a character, add that token to a result list, and then act on the rest of the list. Currently on the last call of (first-item(rest L)) it sends an empty list and then my let statement fails because it can't work on the empty list. How do I add an exit clause or have my function end on the empty list?

(define(first-item L)
  (let ([item (first L)])
    (cond
      [(regexp-match #rx"[-()+*]" (make-string 1 item)) (first-item (rest L))]
      [(regexp-match #px"[0-9]" (make-string 1 item)) (first-item (rest L))]
     )
   )
 )
1 Answers

You need to have your function handle L being empty, whatever that action is.

(define (first-item L)
  (if (empty? L)
    #| exit |#
    #| recursive call |#))
    
Related