Trying to create a recursive function in scheme? - recursion

I'm having a little trouble creating a recursive function in Scheme. I need to create a function called foo(x) that recursively does the addition of all the powers. For example foo(5) would be 5^4 + 4^3 + 3^2 + 2^1 + 1^0 = 701.
The stopping condition is if x = 0 then return zero. Else then return x^x-1 + foo(x-1)
Here's what I have so far for my function:
(define (foo x)
(cond ((zero? x) 0)
(else (+(expt(x (- x 1)))foo(- x 1)))))

You just have to be more careful with the parentheses, in particular notice that the correct way to call a procedure is like this: (foo x), instead of this: foo(x). This should work:
(define (foo x)
(cond ((zero? x) 0)
(else (+ (expt x (- x 1))
(foo (- x 1))))))
(foo 5)
=> 701

Allow me to ident the code. I just pasted it in DrRacket and hit CTRL+I then put the arguments to + on one line each:
(define (foo x)
(cond ((zero? x) 0)
(else (+ (expt (x (- x 1)))
foo
(- x 1)))))
So the base case is ok, but your default case looks very off. x is treated as a procedure since it has parentheses around it and - also uses x as if it's a number. It can't be both.
foo is not applied since it doesn't have parentheses around it so it evaluates to a procedure value, while + would expect all its arguments to be numeric.
The rules of Scheme are that parentheses matters. x and (x) are two totally different things. The first x can be any value, but (x) is an application so x have to evaluate to a procedure. Some exceptions are for special forms you need to know by heart like cond, and define but rather than that it's very important to know you change the meaning of a program by adding parentheses.
The correct definition of your procedure might be:
(define (foo x)
(if (zero? x)
0
(+ (expt x (- x 1))
(foo (- x 1)))))
(foo 5) ; ==> 701
Here I've changed cond to if since none of conds features were used. Seeing cond I expect either side effects or more than one predicate.

Related

Prime Counting using Scheme

I have created two different methods, using SCHEME, to count how many primes exist between 1 and n. I can't understand why the second method doesn't work.
The one that works -
define (count-primes t)
(cond((= t 1) 0)
((prime? t) (+ 1 (count-primes (- t 1))))
(else (count-primes(- t 1)))
)
The one that doesn't work -
(define x 0)
(define (count-primes t)
(cond((= t 1) x)
((prime? t) (+ x 1) (count-primes (- t 1)))
(else (count-primes(- t 1)))
)
)
The problem is with (+ x 1) expression. If you want to increment some variable in Scheme, you have to assign new value to it's name:
(set! x (+ x 1))
It's not enough to simply add some values like you did. It just adds them and then ignores the result because you did not specify what to do with it.
You can also redefine this function to take one more, optional argument and pass x this way, avoiding defining and mutating x separately. Something like:
(define (count-primes t . x)
(cond ((= t 1) (car x))
((prime? t) (+ x 1) (count-primes (- t 1) (+ (car x) 1)))
(else (count-primes (- t 1) (car x)))))
Note you have to take car of x, because x is actually a list of all optional arguments, but we use only first one, so - car.

Scheme Make list of all pair permutations of elements in two equal length lists

I am trying to combine two lists of x coordinates and y coordinates into pairs in scheme, and I am close, but can't get a list of pairs returned.
The following can match up all the pairs using nested loops, but I'm not sure the best way to out put them, right now I am just displaying them to console.
(define X (list 1 2 3 4 5))
(define Y (list 6 7 8 9 10))
(define (map2d X Y)
(do ((a 0 (+ a 1))) ; Count a upwards from 0
((= a (length X) ) ) ; Stop when a = length of list
(do ((b 0 (+ b 1))) ; Count b upwards from 0
((= b (length Y) ) ) ; Stop when b = length of second list
(display (cons (list-ref X a) (list-ref Y b))) (newline)
))
)
(map2d X Y)
I am looking to have this function output
((1 . 6) (1 . 7) (1 . 8) ... (2 . 6) (2 . 7) ... (5 . 10))
I will then use map to feed this list into another function that takes pairs.
Bonus points if you can help me make this more recursive (do isn't 'pure' functional, right?), this is my first time using functional programming and the recursion has not been easy to grasp. Thanks!
The solutions of Óscar López are correct and elegant, and address you to the “right” way of programming in a functional language. However, since you are starting to study recursion, I will propose a simple recursive solution, without high-level functions:
(define (prepend-to-all value y)
(if (null? y)
'()
(cons (cons value (car y)) (prepend-to-all value (cdr y)))))
(define (map2d x y)
(if (null? x)
'()
(append (prepend-to-all (car x) y) (map2d (cdr x) y))))
The function map2d recurs on the first list: if it is empty, then the cartesian product will be empty; otherwise, it will collect all the pairs obtained by prepending the first element of x to all the elements of y, with all the pairs obtained by applying itself to the rest of x and all the elements of y.
The function prepend-to-all, will produce all the pairs built from a single value, value and all the elements of the list y. It recurs on the second parameter, the list. When y is empty the result is the empty list of pairs, otherwise, it builds a pair with value and the first element of y, and “conses” it on the result of prepending value to all the remaining elements of y.
When you will master the recursion, you can pass to the next step, by learning tail-recursion, in which the call to the function is not contained in some other “building” form, but is the first one of the recursive call. Such form has the advantage that the compiler can transform it into a (much) more efficient iterative program. Here is an example of this technique applied to your problem:
(define (map2d x y)
(define (prepend-to-all value y pairs)
(if (null? y)
pairs
(prepend-to-all value (cdr y) (cons (cons value (car y)) pairs))))
(define (cross-product x y all-pairs)
(if (null? x)
(reverse all-pairs)
(cross-product (cdr x) y (prepend-to-all (car x) y all-pairs))))
(cross-product x y '()))
The key idea is to define an helper function with a new parameter that “accumulates” the result while it is built. This “accumulator”, which is initialized with () in the call of the helper function, will be returned as result in the terminal case of the recursion. In this case the situation is more complex since there are two functions, but you can study the new version of prepend-to-all to see how this works. Note that, to return all the pairs in the natural order, at the end of the cross-product function the result is reversed. If you do not need this order, you can omit the reverse to make the function more efficient.
Using do isn't very idiomatic. You can try nesting maps instead, this is more in the spirit of Scheme - using built-in higher-order procedures is the way to go!
; this is required to flatten the list
(define (flatmap proc seq)
(fold-right append '() (map proc seq)))
(define (map2d X Y)
(flatmap
(lambda (i)
(map (lambda (j)
(cons i j))
Y))
X))
It's a shame you're not using Racket, this would have been nicer:
(define (map2d X Y)
(for*/list ([i X] [j Y])
(cons i j)))

Scheme: How do we write recursive procedure with lambda?

I was going through Structure and interpretation of computer programming by Brain harvey. I came across this question which i could not figure out how to do it.
How do we write recursive procedure with lambda in Scheme?
TL;DR: Use named let (if you are executing a recursive function immediately) or rec (if you are saving the recursive function for later execution).
The usual way is with letrec, or something that uses a letrec behind the scenes, like named let or rec. Here's a version of (factorial 10) using letrec:
(letrec ((factorial (lambda (x)
(if (< x 1) 1
(* (factorial (- x 1)) x)))))
(factorial 10))
And the same thing using named let:
(let factorial ((x 10))
(if (< x 1) 1
(* (factorial (- x 1)) x)))
The key understanding here is that both versions are exactly the same. A named let is just a macro that expands to the letrec form. So because the named let version is shorter, that is usually the preferred way to write a recursive function.
Now, you might ask, what if you want to return the recursive function object directly, rather than execute it? There, too, you can use letrec:
(letrec ((factorial (lambda (x)
(if (< x 1) 1
(* (factorial (- x 1)) x)))))
factorial)
There, too, is a shorthand for this, although not using named let, but instead using rec:
(rec (factorial x)
(if (< x 1) 1
(* (factorial (- x 1)) x)))
The nice thing about using rec here is that you can assign the function object to a variable and execute it later.
(define my-fact (rec (factorial x)
(if (< x 1) 1
(* (factorial (- x 1)) x))))
(my-fact 10) ; => 3628800
The more theoretical and "pure" way to create recursive functions is to use a Y combinator. :-) But most practical Scheme programs do not use this approach, so I won't discuss it further.
No need to write factorial body twice ;)
(((lambda (f)
(lambda (x)
(f f x)))
(lambda (fact x)
(if (= x 0) 1 (* x (fact fact (- x 1)))))) 5)
Here is a recursive function that calculates the factorial of 5 using lambda
((lambda (f x)
(if (= x 0)
1
(* x (f f (- x 1)))))
(lambda (f x)
(if (= x 0)
1
(* x (f f (- x 1)))))
5)
When you run this program in Drracket you get 120 :)

In Scheme, how do you use lambda to create a recursive function?

I'm in a Scheme class and I was curious about writing a recursive function without using define. The main problem, of course, is that you cannot call a function within itself if it doesn't have a name.
I did find this example: It's a factorial generator using only lambda.
((lambda (x) (x x))
(lambda (fact-gen)
(lambda (n)
(if (zero? n)
1
(* n ((fact-gen fact-gen) (sub1 n)))))))
But I can't even make sense of the first call, (lambda (x) (x x)): What exactly does that do? And where do you input the value you want to get the factorial of?
This is not for the class, this is just out of curiosity.
(lambda (x) (x x)) is a function that calls an argument, x, on itself.
The whole block of code you posted results in a function of one argument. You could call it like this:
(((lambda (x) (x x))
(lambda (fact-gen)
(lambda (n)
(if (zero? n)
1
(* n ((fact-gen fact-gen) (sub1 n)))))))
5)
That calls it with 5, and returns 120.
The easiest way to think about this at a high level is that the first function, (lambda (x) (x x)), is giving x a reference to itself so now x can refer to itself, and hence recurse.
The expression (lambda (x) (x x)) creates a function that, when evaluated with one argument (which must be a function), applies that function with itself as an argument.
Your given expression evaluates to a function that takes one numeric argument and returns the factorial of that argument. To try it:
(let ((factorial ((lambda (x) (x x))
(lambda (fact-gen)
(lambda (n)
(if (zero? n)
1
(* n ((fact-gen fact-gen) (sub1 n)))))))))
(display (factorial 5)))
There are several layers in your example, it's worthwhile to work through step by step and carefully examine what each does.
Basically what you have is a form similar to the Y combinator. If you refactored out the factorial specific code so that any recursive function could be implemented, then the remaining code would be the Y combinator.
I have gone through these steps myself for better understanding.
https://gist.github.com/z5h/238891
If you don't like what I've written, just do some googleing for Y Combinator (the function).
(lambda (x) (x x)) takes a function object, then invokes that object using one argument, the function object itself.
This is then called with another function, which takes that function object under the parameter name fact-gen. It returns a lambda that takes the actual argument, n. This is how the ((fact-gen fact-gen) (sub1 n)) works.
You should read the sample chapter (Chapter 9) from The Little Schemer if you can follow it. It discusses how to build functions of this type, and ultimately extracting this pattern out into the Y combinator (which can be used to provide recursion in general).
You define it like this:
(let ((fact #f))
(set! fact
(lambda (n) (if (< n 2) 1
(* n (fact (- n 1))))))
(fact 5))
which is how letrec really works. See LiSP by Christian Queinnec.
In the example you're asking about, the self-application combinator is called "U combinator",
(let ((U (lambda (x) (x x)))
(h (lambda (g)
(lambda (n)
(if (zero? n)
1
(* n ((g g) (sub1 n))))))))
((U h) 5))
The subtlety here is that, because of let's scoping rules, the lambda expressions can not refer to the names being defined.
When ((U h) 5) is called, it is reduced to ((h h) 5) application, inside the environment frame created by the let form.
Now the application of h to h creates new environment frame in which g points to h in the environment above it:
(let ((U (lambda (x) (x x)))
(h (lambda (g)
(lambda (n)
(if (zero? n)
1
(* n ((g g) (sub1 n))))))))
( (let ((g h))
(lambda (n)
(if (zero? n)
1
(* n ((g g) (sub1 n))))))
5))
The (lambda (n) ...) expression here is returned from inside that environment frame in which g points to h above it - as a closure object. I.e. a function of one argument, n, which also remembers the bindings for g, h, and U.
So when this closure is called, n gets assigned 5, and the if form is entered:
(let ((U (lambda (x) (x x)))
(h (lambda (g)
(lambda (n)
(if (zero? n)
1
(* n ((g g) (sub1 n))))))))
(let ((g h))
(let ((n 5))
(if (zero? n)
1
(* n ((g g) (sub1 n)))))))
The (g g) application gets reduced into (h h) application because g points to h defined in the environment frame above the environment in which the closure object was created. Which is to say, up there, in the top let form. But we've already seen the reduction of (h h) call, which created the closure i.e. the function of one argument n, serving as our factorial function, which on the next iteration will be called with 4, then 3 etc.
Whether it will be a new closure object or same closure object will be reused, depends on a compiler. This can have an impact on performance, but not on semantics of the recursion.
I like this question. 'The scheme programming language' is a good book. My idea is from Chapter 2 of that book.
First, we know this:
(letrec ((fact (lambda (n) (if (= n 1) 1 (* (fact (- n 1)) n))))) (fact 5))
With letrec we can make functions recursively. And we see when we call (fact 5), fact is already bound to a function. If we have another function, we can call it this way (another fact 5), and now another is called binary function (my English is not good, sorry). We can define another as this:
(let ((another (lambda (f x) .... (f x) ...))) (another fact 5))
Why not we define fact this way?
(let ((fact (lambda (f n) (if (= n 1) 1 (* n (f f (- n 1))))))) (fact fact 5))
If fact is a binary function, then it can be called with a function f and integer n, in which case function f happens to be fact itself.
If you got all the above, you could write Y combinator now, making a substitution of let with lambda.
With a single lambda it's not possible. But using two or more lambda's it is possible. As, all other solutions are using three lambdas or let/letrec, I'm going to explain the method using two lambdas:
((lambda (f x)
(f f x))
(lambda (self n)
(if (= n 0)
1
(* n (self self (- n 1)))))
5)
And the output is 120.
Here,
(lambda (f x) (f f x)) produces a lambda that takes two arguments, the first one is a lambda(lets call it f) and the second is the parameter(let's call it x). Notice, in its body it calls the provided lambda f with f and x.
Now, lambda f(from point 1) i.e. self is what we want to recurse. See, when calling self recursively, we also pass self as the first argument and (- n 1) as the second argument.
I was curious about writing a recursive function without using define.
The main problem, of course, is that you cannot call a function within
itself if it doesn't have a name.
A little off-topic here, but seeing the above statements I just wanted to let you know that "without using define" does not mean "doesn't have a name". It is possible to give something a name and use it recursively in Scheme without define.
(letrec
((fact
(lambda (n)
(if (zero? n)
1
(* n (fact (sub1 n)))))))
(fact 5))
It would be more clear if your question specifically says "anonymous recursion".
I found this question because I needed a recursive helper function inside a macro, where one can't use define.
One wants to understand (lambda (x) (x x)) and the Y-combinator, but named let gets the job done without scaring off tourists:
((lambda (n)
(let sub ((i n) (z 1))
(if (zero? i)
z
(sub (- i 1) (* z i)) )))
5 )
One can also put off understanding (lambda (x) (x x)) and the Y-combinator, if code like this suffices. Scheme, like Haskell and the Milky Way, harbors a massive black hole at its center. Many a formerly productive programmer gets entranced by the mathematical beauty of these black holes, and is never seen again.

Position Independent Parameters to Scheme Functions

How do I pass position-independent parameters to scheme functions?
In PLT Scheme you can use:
(define area
(lambda (x #:width y)
(* x y)))
(area 3 #:width 10)
or
(area #:width 10 3)
both would return 30.
There's no standard support for this in scheme but have a look at this
I am not a scheme guru, but I'm thinking that parameters need to be a pair rather than an atom, then you make a parameter list from your pairs and use a let block to bind the values to actual parameters. And, for the love of all that is beautiful, call a helper function to do the actual work with the parameters in the right order since calling get-param in recursion is going to get expensive.
(define get-param (lambda (name pair-list)
(cond ((null? pair-list) nil)
((eq? name (caar pair-list)) (cadr (car pair-list)))
(t (get-param name (cdr pair-list))))))
; position independent subtract always subtracts y from x
; usage (f '(x 7) '(y 9)) => -2
; (f '(y 9) '(x 7)) => -2
(define f (lambda (x-pair y-pair)
(let ((pl (list x-pair y-pair))
(let ((x (get-param 'x pl)) (y (get-param 'y pl))
(- x y)))))
Someone who is really clever would make a factory function that would take an arbitrary lambda expression and build an equivalent position independent lambda from it.

Resources