I'm studying Scheme language (by myself). Recently I've encountered this question:
There are two functions which compute the same value (compose function f - n times).
(define (repeated f n)
(lambda (x)
(if (= n 1)
(f x)
(f ((repeated f (- n 1)) x)))))
(define (repeated f n)
(if (= n 1)
f
(lambda (x)
(f ((repeated f (- n 1)) x)))))
As I understood these two are not recursive procedures but they return recursive procedures (lol). So what is the difference between these two? Is it possible that the first returns already computed procedure even before I give value to X? I'm so confused... Please help.
In fact both procedures are recursive, each one is calling itself at some point during the execution. Also, both are returning a lambda at some point - meaning: they're procedures that return procedures.
The first procedure always returns a lambda, whereas the second procedure short-circuits and returns f when n equals 1, but also returns a lambda for values of n greater than 1. So they're not different, except for the way the base case (n equals 1) is handled.
Wow that's so much simpler than mine, though mine is tail-recursive and works for (repeated fn 0) asuuming that running a function zero times on an argument is just that argument.
(define (repeated fn times)
(let loop (
(continuation (lambda (x) x))
(count-down times))
(if (not (> count-down 0))
(lambda (x) (continuation x))
(loop (lambda (x) (continuation (fn x))) (- count-down 1)))))
The difference between the two of yours is that the first returns a procedure right-away, and then calls itself as part of the procedure. The second returns a procedure only after it's fully calculated what that procedure will be.
Right so the first returns a recursive procedure, while the second used recursion to return a non-recursive procedure. Mine works more like the second, but can calculate repitition for very large numeric values while the two above will exceed the maximum recursion depth.
((repeated cdr 1000000) (iota 1000589))
Related
So from my personal research, it seems that closures / currying seem to be more or less the exact same thing, which can't be obviously correct. So where is the difference?
So here is an example of a closure in Racket:
(define (make-an-adder x)
(lambda (y)
(+ y x)))
(define add3 (make-an-adder 3))
(add3 5)
will give back
8
So where is the difference to currying? Because if i look up documentations and other examples, it seems that they do the exact same thing as i showed for the closure?
Thanks in advance everyone!
So they are different concepts, but both are related to nested lambdas.
A Closure can be created by a lambda that refers to a variable defined outside itself, and is most important when the lambda escapes from the context where that outside variable is defined. The Closure's job is to make sure that variable is preserved when the lambda escapes that context.
A Curried function is a function that can take its arguments in multiple steps, or multiple different function-applications. This normally means there are lambdas nested within lambdas.
Curried functions aren't always closures, though they often are
Most useful curried functions need to use closures, but if the inner lambdas ignore the outer arguments, they aren't closures. A simple example:
(define (curried-ignore-first ignored)
(lambda (y) y))
This is not a closure because the inner lambda (lambda (y) y) is already closed: it doesn't refer to any variables outside itself.
A curried function doesn't always need to ignore the outer arguments... it just needs to be done processing them before it returns the inner lambda, so that the inner lambda doesn't refer to the outer argument. A simple example of this is a curried choose function. The "normal" definition of choose does indeed use a closure:
(define (choose b)
(lambda (x y)
(if b x y))) ; inner lambda refers to `b`, so it needs a closure
However, if the if b is put outside the outer lambda, we can avoid making closures:
(define (choose b)
(if b
(lambda (x y) x) ; not closures, just nested lambdas
(lambda (x y) y)))
Closures aren't always from curried functions
A closure is needed when a inner lambda refers to a variable in an outer context and might escape that context. That outer context is often a function or a lambda, but it doesn't have to be. It can be a let:
(define closure-with-let
(let ([outer "outer"])
(lambda (ignored) outer))) ; closure because it refers to `outer`
This is a closure, but not an example of currying.
Turning a Curried-function-producing-a-closure into one without a closure
The example in the original question is a curried function that produces a closure
(define (make-an-adder x)
(lambda (y)
(+ y x)))
If you wanted to make a version that's still a curried function with the same behavior, but without needing a closure over x in some special cases, you can branch on those before the lambda:
(define (make-an-adder x)
(match x
[0 identity]
[1 add1]
[-1 sub1]
[2 (lambda (y) (+ y 2))]
[3 (lambda (y) (+ y 3))]
[_ (lambda (y) (+ y x))]))
This avoids producing a closure for the cases of x being an exact integer -1 through 3, but still produces a closure in all other cases of x. If you restricted the domain of x to a finite set, you could turn it into a function that didn't need closures, just by enumerating all the cases.
If you don't want a closure over x, but you're fine with a closure over other things, you can use recursion and composition to construct an output function that doesn't close over x:
(define (make-an-adder x)
(cond [(zero? x) identity]
[(positive-integer? x)
(compose add1 (make-an-adder (sub1 x)))]
[(negative-integer? x)
(compose sub1 (make-an-adder (add1 x)))]))
Note that this still produces closures (since compose creates closures over its arguments), but the function it produces does not close over x. Once this version of make-an-adder produces its result, it's "done" processing x and doesn't need to close over it anymore.
I am new to Racket and functional languages in general. For now I am just trying to prepend items to a list. The concepts are a bit confusing and not sure why my code isn't working.
I am trying to do dot product calculations.
I have a function called "dProduct" that takes 2 lists (A and B) and multiplies each corresponding element in them.
;function takes dot product
(define (dProduct A B)
(define C '()) ; define list to store the multiplied elements
;multiply ea lists elements
(for ([i A] [j B])
(display (* i j)) ;THIS WORKS
(cons (* i j) C) ;APPARENTLY DOESN'T WORK
)
;THIS FOR LOOP DISPLAYS NOTHING
;display the new list "C"
(for ([k C])
(display k)
)
)
I don't understand why I can't use cons to prepend the new multiplied elements to my new list "C". What am I missing? Everything compiles fine. Would like to figure this out so I can finish this function :) Any help would be great. Thanks!
Lists are immutable, and cons does not prepend an element to an existing list. Instead, it produces a new list with the element prepended:
> (define x '(2 3))
> (cons 1 x)
'(1 2 3)
> x
'(2 3)
Since your question is tagged functional-programming, I will assume that you probably want to know how to do this functionally, and functional programming generally discourages mutating values or bindings.
Instead of mutating a binding, you should build up a new structure functionally. The easiest way to do this is to change your use of for to for/list, which produces a list of return values:
(define C
(for/list ([i A] [j B])
(* i j)))
For this program, you could make it even simpler by using the higher-order function map, which acts like a “zip” when provided more than one list argument:
(define C (map * A B))
Since for always returns #<void>, it’s only useful for producing side-effects, and in functional programming, you generally try and keep side-effects to a minimum. For that reason, you will likely find that for/list and for/fold are actually much more commonly useful in idiomatic Racket than plain for is.
Current C list has to be given new value of (cons (* i j) C) and this can be done using set! :
(define (dProduct A B)
(define C '())
(for ([i A] [j B])
(displayln (* i j))
(set! C (cons (* i j) C))) ; NOTE set! HERE.
(for ([k C])
(displayln k)))
Note that the use of set! is strongly discouraged and for/list is much better way to achieve desired result here.
I'm having trouble incorporating a recursive function that squares a number.
Basically I am trying to write a function that keeps calling the Add function x number of times to square it. So if it is 7 it should call it seven times to get 49.
(define (Add a b)
(if (and (number? a) (number? b))
(+ a b)
(lambda (x)
(+ (a x) (b x)))))
(define i 0)
(define ans 0)
(define (Square a)
(when (> i a)
((Add a ans) (+ i 1 ))))
The main issue I'm running into is that the square function only goes through the loop once, I'm not sure why the condition won't update/keep going through the loop till it reaches that condition.
Writing square directly is a big pain. It's much easier to write a recursive multiply function and then just have your square function call multiply. Follow the design recipe for recursion on the natural numbers, as it appears in section 9.3 of HtDP.
By the way, if you haven't already written a bunch of recursive functions on more standard self-referential data definitions (e.g. lists), then, well, I claim that your instructor is doing in wrong.
You should make everything that changes parameters. Imagine you want to make the factorial then two values change. It's the result and the iteration of the number down to zero.
(define (factorial value)
(define (helper cur ans)
(if (zero? cur)
ans ; finished. return the answer
(helper (- cur 1) ; recur by updating n
(* cur ans)))) ; and update the answer
(helper value 1))
Again. It's exactly the same as my example in the comment except it does something else at each step. The basic building blocks are the same and something that would square the argument is very similar.
I'm reading The Little Schemer and feel confused about the following code:
((lambda (len)
(lambda (l)
(cond
((null? l) 0)
(else
(+ 1 (len (cdr l)))))))
eternity)
(define eternity
(lambda (x)
(eternity x)))
The code is to determine the empty list, otherwise it never stops.
Why is the "len" not recursion?
Although it can be dangerous to apply textual substitution to Lisp forms (since there are dangers of multiple evaluation, etc.), in this case it may help to look at this form and see how it fits together:
((lambda (len)
(lambda (l)
...))
eternity)
is an application, i.e., a function call. The function getting called takes one argument, called len, and returns another function that takes a single argument l. The function getting called is called with eternity. When the call completes, the result is this function:
(lambda (l)
(cond
((null? l) 0)
(else (+ 1 (eternity (cdr l))))))
Now, this function takes a list l and if it's empty, returns 0. Otherwise, it computes (cdr l) (the rest of the list), and calls eternity with that value. When that returns, 1 is added to the result, and that's the return value of the whole function. The problem, of course, is that eternity
(define eternity
(lambda (x)
(eternity x)))
which could also be written as
(define (eternity x)
(eternity x))
simply takes an argument x, and then calls eternity with x. That's an infinite loop. In the above, I wrote "When that returns", but in fact, (eternity (cdr l)) never returns. So,
((lambda (len)
(lambda (l)
(cond
((null? l) 0)
(else (+ 1 (len (cdr l)))))))
eternity)
is a function call that returns a function (lambda (l) …) that returns 0 if called with an empty list, and goes into an infinite loop with a non-empty list.
From a program analysis side of things, it's worth noting that there are other values for which this won't go into an infinite loop. For instance, if you call it with a string, then (cdr l) will be an error.
Like you say, this is a definition of a length function as a partial function where it only completes for the empty list. But this hasn't gotten to the y-combinator part yet, it isn't an example of an anonymous function calling itself.
l is a list of atoms, it is the argument to the function returned when (lambda (len) ...) is evaluated.
len is a function passed into the outer lambda as an argument.
The outer expression creates a lambda with eternity passed in as its argument. The outer lambda returns a function created by evaluating the inner lambda, the returned function is the thing that takes eternity as an argument.
If the code is passed an empty list (meaning wrap the whole first part followed by a '() in another set of parens) then it will evaluate to 0, of course. len never gets evaluated.
If the code is passed a nonempty lat then it will try to evaluate the len argument and you get an infinite recursion.
#lang eopl
(define (expo base n )
(cond( (or (= base 1) (= n 0) ) 1)
(else ( (* base (expo(base (- n 1))) ) ) )))
-> (enter! "expo.rkt")
"expo.rkt"> (expo (2 1) )
; application: not a procedure;
; expected a procedure that can be applied to arguments
; given: 2
; [,bt for context]
I am trying to create a simple recursive exponentiation, but I get the error above. Code is self-explanatory. I am a newbie in Racket programming. I have been reading the manuals, but can't find my error. Supposedly, it shows the error because my function returns a void and not a procedure, but I don't see why it would return void. I am returning 1 or a computation.
Help, please :/
You have several misplaced parentheses. This should solve the errors:
(define (expo base n)
(cond ((or (= base 1) (= n 0)) 1)
(else (* base (expo base (- n 1))))))
And this is how you call it:
(expo 2 3)
=> 8
For the record: in Scheme a pair of parentheses means function application, so when you write (2 3) the interpreter thinks that 2 is a function and 3 is its argument ... clearly that won't work.
So you'll have to be very careful where you put those (), they make all the difference in the world! To make things easier use a good IDE with bracket matching and nice syntax coloring, and be extra tidy with the indentation. As suggested by #dyoo in the comments, DrRacket is an excellent choice.
When you call the function, you want to write
(expo 2 1)
rather than
(expo (2 1))
Same in the definition of the recursive function's definition.
In addition, this part have double brackets, which is unnecessary.
( (* base (expo(base (- n 1))) )
The cond syntactic form is best used when a) you have more than two clauses or b) you have a sequence of commands/expressions to perform for one or more clauses. Those two cases don't apply to your code. Thus, you'd have clearer code (easier to understand; easier to get correct) using if as such:
(define (expo base n)
(if (or (= base 1) (= n 0))
1
(* base (expo base (- n 1)))))
Also, study the spacing and indentation of some 'good' code; it will help your understanding tremendously.