Learning Scheme

Exercise: Write a function that returns the length of a list (without using the scheme length function).

My try:

(define mylengh
  (lambda (ilist)
    (letrec ((mylengh-rec
               (lambda (rlist nr)
                 (if (eqv? rlist '()) nr
                   (mylengh-rec (cdr rlist) (+ nr 1))))))
             (mylengh-rec ilist 0))))

Solution:

(define (mylength a)
  (if (null? a) 0
      (+ 1 (mylength (cdr a)))))

Well… It is a start. :)

2 Responses to “Learning Scheme”

  1. Tabgal Says:

    Em Haskell ficou (também não sou especialista :P)

    len :: [a] -> Int
    len [] = 0
    len (x:ys) = 1 + len ys

  2. Eduardo Habkost Says:

    Your solution actually has a point: it does tail recursion and won’t abuse the function-call stack, like the simpler solution probably will.