guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: help : call function with args


From: calcium
Subject: Re: help : call function with args
Date: Thu, 5 Apr 2018 11:42:08 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.7.0

> Not sure what you aim at.
> Though, above seems to be easier with:
> 
> (define (f . rest) (apply + rest))
> 
> (f)
> -> 0
> (f 1 2 3)
> -> 6
> (f 1 2 3 4 5 6 7 8 9 10)
> -> 55
> 
> Cheers,
>   Harm
> 

yes, it easier for this function, but when we have functions with
different "types" like the one bellow , i find it nice to only call once
the function, instead of copy-past the common args and then giving the
different args for each cond branch.

Although, the example that i give, it way more elegant and readable the
second than the first, but i believes that sometimes the first can be
more compact an elegant than the second one.

(define lst
  (list 1 3 5 9 10 2 1 2 20 4 9 15))


;;sort the list so that the biggest element is the first element
;;and the rest without a particular order.

;;write once the function

(let sort ((preLst (cdr lst))
           (postLst '())
           (biggest (car lst)))
  (cond ((nil? preLst)
         (cons biggest postLst))
        (else (let ((post (cons (car preLst) postLst))
                    (big biggest))
                (cond ((> (car preLst) biggest)
                       (set! big (car preLst))
                       (set! post (cons biggest postLst))))
                (sort (cdr preLst) post big)))))

;; instead of writing

(let sort ((preLst (cdr lst))
           (postLst '())
           (biggest (car lst)))
  (cond ((nil? preLst)
         (cons biggest postLst))
        (else (cond ((> (car preLst) biggest)
                     (sort (cdr preLst) ;; the common arg
                           (cons biggest postLst)
                           (car preLst)))
                    (else
                     (sort (cdr preLst) ;;the common arg
                           (cons (car preLst) postLst)
                           biggest))))))
Cheers,
 Calcium



reply via email to

[Prev in Thread] Current Thread [Next in Thread]