Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

First CLISP functions of a babby

Name: EXPERT BABBY 2011-01-22 16:41

Hey /prague/,
what do you think of my first functions? Do you think i am corrupted by the procedural paradigm already?


(defun factorial (a)
    "Calcula el factorial de a"
    (if (< a 1)
        1
        (* a (factorial (- a 1)))))

(defun get-n-elements (a n)
    "Crea una lista con los n primeros elementos de a,
    si a tiene menos de n elementos, rellena los elementos
    restantes con NIL"
    (cond
        ((<= n 0) nil)
        (T (append (list (car a)) (get-n-elements (rest a) (- n 1))))))
       

(defun get-n-to-m-elements (a n m)
    "Crea una lista con los elementos entre n y m de a"
    (cond
        ((not a) nil)
        ((> n m) (get-n-to-m-elements a m n))
        (T (reverse (get-n-elements (reverse (get-n-elements a m)) (+ (- m n) 1))))))

Name: Anonymous 2011-01-22 20:08

>>12
Not saying Racket is bad, however Common Lisp is pretty powerful if you know it well, and personally I prefer CL to Scheme. It's a matter of personal taste.

>>1
Here's some ENTERPRISE CL implementation of your code:

(defun range (start-or-count &optional (end (1- start-or-count) end-present-p)
        (by 1) &aux (start (if end-present-p start-or-count 0))) 
  (loop for i from start to end by by collect i))

(defun fact (n)
  (reduce #'* (range 1 n) :initial-value 1))

;; or more imperative (and faster)
(defun fact (n)
  (loop for i from 1 to n
    for result = 1 then (* result i)
    finally (return result)))

;; helper function which extends the sequence to length n if needed (because your code does that in get-n-elements)
(defun ensure-length (sequence n)
  (if (< (length sequence) n)
      (replace (make-sequence (class-of sequence) n :initial-element nil)
           sequence)
      sequence))

;; same as get-n-elements, but works on all kinds of sequences (lists, arrays, ...). In general, it would be best to just use subseq
(defun take (sequence n) 
  (subseq (ensure-length sequence n) 0 n))

;; again, use subseq instead, however to retain the same functionality as your code, I'm ensuring length is as expected (nil's will be added as needed)
(defun get-n-to-m-elements (sequence start end)
  (subseq (ensure-length sequence end) (1- start) end))

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List