unj2
unj2

Reputation: 53481

How do I apply a symbol as a function in Scheme?

Is there a way I can apply '+ to '( 1 2 3)?

edit: what i am trying to say is that the function i get will be a symbol. Is there a way to apply that?

Thanks.

Upvotes: 6

Views: 4549

Answers (6)

Alexey Grigorev
Alexey Grigorev

Reputation: 2425

In Racket's scheme it would be

#lang scheme

(define ns (make-base-namespace))
(apply (eval '+ ns) '(1 2 3))

Upvotes: 1

Jyaan
Jyaan

Reputation: 505


;; This works the same as funcall in Common Lisp:
(define (funcall fun . args)
  (apply fun args))

(funcall + 1 2 3 4) => 10
(funcall (lambda (a b) (+ a b) 2 3) => 5
(funcall newline) => *prints newline*
(apply newline) => *ERROR*
(apply newline '()) => *prints newline*

Btw, what's the deal with this "syntax highlighting" ??

Upvotes: 1

Davorak
Davorak

Reputation: 7444

In R5RS you need

(apply (eval '+ (scheme-report-environment 5)) '(1 2 3))

The "Pretty Big" language in Dr. Scheme allows for:

(apply (eval '+) '(1 2 3))

Upvotes: 4

micmoo
micmoo

Reputation: 6081

How about the scheme "apply"

(apply + `(1 2 3)) => 6

I hope that was what you were asking :)

Upvotes: -1

Rainer Joswig
Rainer Joswig

Reputation: 139251

How about 'apply'? Use the variable + instead of the symbol + .

(apply + '(1 2 3))

R5RS

Upvotes: 1

Ben Hughes
Ben Hughes

Reputation: 14185

(apply (eval '+) '(1 2 3))

Should do it.

Upvotes: 7

Related Questions