John
John

Reputation: 837

How can I declare a function that takes in a function as parameter in Scheme

I want to declare a function that takes in a function(the function also takes a element as parameter) and a list as parameters in Scheme

but the is line of code gives me error (define (function funct(x),l)

Upvotes: 1

Views: 2027

Answers (2)

itsbruce
itsbruce

Reputation: 4843

Scheme does not allow you to specify the parameter types in the function definition. The best you can do is

(define my-func(func . args)

Which will give you the first argument in the func parameter and all the rest in a list in args. You can then check the type of ** func **, if you want, before applying it to the args.

(cond
  ((procedure? func) (func args))
  (else (report some kind of error however you want)))

Upvotes: 0

João Silva
João Silva

Reputation: 91349

In Scheme, functions are first-class citizens. Thus, you can pass a function as a parameter to another function, just like you do with any other symbol. There's no such thing as the function keyword.

For example, to define a function called map that takes a function as an argument, and applies it to every member of the list, you could use:

(define (map f l)
  (if (null? l)
      l
      (cons (f (car l)) (map f (cdr l)))))

Then, if you had a function called add1 that you wanted to pass to map:

(define (add1 x)
  (+ x 1))

(map add1 '(1 2 3))

The result would be (2 3 4).

DEMO.

Upvotes: 1

Related Questions