Reputation: 587
Ok so I've spent quite a lot of time on this, I can't seem to grasp how to do this. I do understand it quite a bit when it's a simple variable but can't seem to grasp a little more complicated problem with the same concept.
This is the simple one I understand quite a bit:
(define (add n)
(lambda (x) (+ x n)))
(define total (add 5))
(total 12) => **17**
This is what I'm trying to achieve, when an integer is entered it should find the value of that position, I have the function that finds the position already but not sure how to implement this into the function which returns a function way:
(define (position N L)
(cond ((null? L) L)
((= N 1) (car L))
(else (position (- N 1) (cdr L)))))
For example if I enter (define X (position '(1 5 8 2 7)))
and then input (X 4)
it should output 2
which is at position #4. I'm sure it's something simple but I've been sitting here for a while trying to put it together but I'm not doing well. Any help is appreciated!
Upvotes: 1
Views: 536
Reputation: 387
As uselpa said, you could do this by defining a second procedure, but this is a fairly straightforward implementation so you could do something like this:
(define (position L)
(lambda (N)
(cond ((null? L) '())
((= N 1) (car L))
(else ((position (cdr L)) (- N 1))))))
(define X (position '(1 5 8 2 7)))
Here, X is defined as a #<procedure>
bound to the function position
with the list L
. In the else
statement, you see (position (cdr L))
which is equivalent to X
, which we follow with (- N 1)
.
Upvotes: 3
Reputation: 18937
It's easiest to create a second procedure:
(define (position L N)
(cond ((null? L) L)
((= N 1) (car L))
(else (position (cdr L) (- N 1)))))
(define (position2 L)
(lambda (N)
(position L N)))
then
> (define X (position2 '(1 5 8 2 7)))
> (X 4)
2
In Racket, you can also use curry
:
> (define x (curry position '(1 5 8 2 7)))
> (x 4)
2
Upvotes: 3