user3536796
user3536796

Reputation:

Scheme - nested definition confusion

I'm currently stuck on a problem creating func and am a beginner at Scheme. In order to achieve such a result, will I have to define double inside func?

(func double 3 '(3 5 1)) 

would return (24 40 8) because each element is doubled 3 times.

Upvotes: 0

Views: 110

Answers (4)

uselpa
uselpa

Reputation: 18917

No, double needs to be outside func because it will be passed as a parameter (bound to f) to func:

(define (double n) (* 2 n))

(define (times f e t)
  (if (= t 0)
      e
      (times f (f e) (- t 1))))

(define (func f t lst)
  (map (lambda (e) (times f e t)) lst))

then

> (func double 3 '(3 5 1)) 
'(24 40 8)

OTOH, in this case times could be defined inside func, but it's a reusable procedure so I'd leave it outside.

Upvotes: 2

Sylwester
Sylwester

Reputation: 48735

Possibly something like this:

(define (cmap fun arg1 lst)
  (map (lambda (x) (fun arg1 x)) lst))

But really you want to do this (cmap list 1 (get-some-calc x) (get-list)) but it's very difficult to make it take any curried argument and perhaps you want more than one list. You do it like this:

(let ((cval (get-come-calc x)))
  (map (lambda (x) (list 1 cval x)) (get-list)))

Upvotes: 0

soegaard
soegaard

Reputation: 31147

#lang racket

(define (repeat f x n)
  (cond [(= n 0) x]
        [else    (f (repeat f x (- n 1)))]))

(define (func f n xs)
  (map (λ(x) (repeat f x n)) xs))

(define (double x) 
  (* 2 x))

(func double 3 '(3 5 1))

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 222973

If I understand your question correctly, here's one way you can implement func:

(define (func f n lst)
  (do ((n n (sub1 n))
       (lst lst (map f lst)))
      ((zero? n) lst)))

Example usage:

> (func (lambda (x) (* x 2)) 3 '(3 5 1))
=> (24 40 8)

Upvotes: 1

Related Questions