scheme – Example of apply other than + in Racket
scheme – Example of apply other than + in Racket
Just like (apply + (list 1 2 3 4))
is equivalent to (+ 1 2 3 4)
, (apply println (list a b c))
is equivalent to (println a b c)
. However thats not a valid use of println
. As the error message suggests, the second argument should be an output port, not a string.
To correctly call println
using apply
, you must supply a valid argument list, such as:
(apply println (list a))
;; or
(apply println (list a (current-output-port))
Heres some examples of using apply
with functions that take an arbitrary number of arguments and will thus always work regardless of the length of the list:
(apply * (list 1 2 3 4)) ; 24
(apply list (list 1 2 3 4)) ; (list 1 2 3 4) ¹
(apply set (list 1 2 3 4)) ; (set 1 2 3 4)
¹ Well, you wouldnt really use apply
with list
as that just gives you back the same list (or rather a copy of it), but you can.
If you want to apply a procedure eg. (proc a b c)
but the arguments are supplied in a list. You could do (proc (car l) (cadr l) (caddr l))
but you can also just do (apply proc l)
. If you have additional arguments you want in front you can even do (apply proc 5 l)
and it is the same as (proc 5 (car l) (cadr l) (caddr l))
. apply
takes any number of arguments but the very last needs to be a list of the final arguments.
Its important to understand that apply
is not a fold. If you have a procedure that takes exactly one argument then you can apply that with a list of exactly one element or else the procedure will fail..
(cons 1 2) ; ==> (1 . 2)
(apply cons (1 2)) ; ==> (1 . 2)
(cons 1 2 3) ; ==> ERROR cons: arity mismatch
(apply cons (1 2 3)); ==> ERROR cons: arity mismatch
apply
is the opposite of a rest argument:
(define (proc arg1 . argn)
(apply list arg1 argn))
(proc 1 2 3 4) ; ==> (1 2 3 4)
It is not a fold
;; a two arity add
(define (add a b)
(+ a b))
(apply add (1 2)) ; ==> 3
(apply add (1 2 3)) ; ==> ERROR add: arity mismatch
;; foldl is a fold
(foldl add 0 (1 2 3)) ; ==> 6