; Variable Arity ; variable arity is when procedures can take in a variable number of arguments ; what are some builtin variable arity procedures in Scheme? ; list, +, *, string, append, <, >, and, or .... ; to make a variable arity procedure, do not put () around the varible that ; lambda binds ; (define PROC ; (lambda ARGS ; ....)) ; so the procedure PROC takes in any number of arguments and puts them in ; a list called ARGS ; let us pretend the builtin + in Scheme is not variable arity and it must take two ; elements, let us then write add which is a variable arity version of + ;;; add: compute the sum of the values that follow ;;; Givens: ;;; Some number of values, collectively called VALUES ;;; Result: ;;; SUM, a number ;;; Preconditions: ;;; all VALUES are numbers ;;; Postcondition: ;;; SUM is the result of adding the numbers in VALUES (define add (lambda values (let loop ((lst values)) (if (null? lst) 0 (+ (car lst) (loop (cdr lst))) ) ) ) ) ; another syntax for variable arity ; these procedures will filter out numbers outside a specified range. ; filter-1 takes a maximum value, followed by values to filter ; filter-2 takes both a minimum and a maximum ;;; filter-1: filter negatives and large numbers from a number sequence ;;; Givens: ;;; A MAXIMUM allowed value, followed by ;;; Some number of values, collectively called VALUES ;;; Result: ;;; LS: a list of numbers ;;; Preconditions: ;;; MAXIMUM and all VALUES are numbers ;;; Postcondition: ;;; LS contains all numbers in VALUES, provided the numbers are ;;; non-negative and do not exceed MAXIMUM. The order of numbers ;;; on LS is the same as the order in VALUES. (define filter-1 (lambda (maximum . values) ; maximum is the first parameter; values the rest (let loop ((lst values) (result-so-far '())) (cond ((null? lst) (reverse result-so-far)) ((<= 0 (car lst) maximum) (loop (cdr lst) (cons (car lst) result-so-far))) (else (loop (cdr lst) result-so-far)) ) ) ) ) ;;; filter-2: filter values below a minimum or above a maximum from a number sequence ;;; Givens: ;;; A MINIMUM and a MAXIMUM allowed value, followed by ;;; Some number of values, collectively called VALUES ;;; Result: ;;; LS: a list of numbers ;;; Preconditions: ;;; MINIMUM, MAXIMUM, and all VALUES are numbers ;;; Postcondition: ;;; LS contains all numbers in VALUES, provided the numbers are ;;; not below MINIMUM do not exceed MAXIMUM. The order of numbers ;;; on LS is the same as the order in VALUES. (define filter-2 (lambda (minimum maximum . values) (let loop ((lst values) (result-so-far '())) (cond ((null? lst) (reverse result-so-far)) ((<= minimum (car lst) maximum) (loop (cdr lst) (cons (car lst) result-so-far))) (else (loop (cdr lst) result-so-far)) ) ) ) )