I'm writing a function that takes a list and returns the sum of the squares of all items in the list. Called on (1 2 3) it should return 14: (12 + 22 + 32).
I have this sqsum function:
(define (sqsum lis)
(if (null? lis)
0
(+ (* (car lis) (car lis)) (sqsum (cdr lis)))
)
)
Is this tail recursive? I think it is recursive but not tail recursive.
This is part of my homework and I'm not looking for solution: I just want to know if this is tail recursive or not. If not then I need to read more and find new solutions.
To be tail recursive the recursion has to happen at the very last function, i.e. you cannot do anything with the results from the recursiv call. Here you pass it to +, which makes it non-tail-recursive. The compiler could optimize this away though, and it's pretty easy to do yourself too.
No, it is not tail recursive.
The general approach to making a non-tail recursive function tail-recursive is to include an accumulator, which is an extra argument that carries the current evaluation of the procedure through your recursive calls.
Incidentally, this is also where "helper" functions are very useful. The general practice is to define your function so that it does not take the accumulator, define a helper function within it that does take the accumulator, and then have the main function do little besides call the helper function. You'll see what I mean in a sec.
In your case (if I'm remembering my Scheme properly :p):
(define (sqsum lis)
(define (sqsum-h lis acc)
(if (null? lis)
acc
(sqsum-h (cdr lis) (+ acc (* (car lis) (car lis))))
)
)
(sqsum-h lis 0)
)
This is tail-recursive because the last thing any recursive call does is immediately return the result of another function without modifying it.
Related
I have a list that contains the "names" of some functions (for example '(+ - *))
I want to use that list to call the functions
(define list_of_names_of_functions '(+ - *))
(define sum (car list_of_names_of_functions))
(sum 2 3)
However, sum is a list, so can't be used as a procedure.
How should i do it?
The variable list_of_names_of_functions has symbol representation and not the actual function. you should perhaps make an alist with name and function like this:
(define ops `((+ . ,+) (- . ,-) (* . ,*)))
If you evaluate ops you'll see something like:
((+ . #<procedure:+>)
(- . #<procedure:->)
(* . #<procedure:*>))
There is no standard on how a function/procedure object should be represented, but it is expected that that value can be applied as any other function:
((cdar ops) 1 2) ; ==> 3
Thus you can search for + using:
(assq '+ ops)
; ==> (+ . #<procedure:+>)
(assq '/ ops)
; ==> #f
Thus if the result is truthy the cdr will contain a procedure:
(apply (cdr (assq '+ ops)) '(1 2)) ; ==> 3
If you are making a special kid of eval then you would consider the list an environment and it can easily be added to such that you can add /. You can also supply anything callable so an op doesn't need to exist in the host system. eg. `(square . ,(lambda (v) (* v v)) works as well.
Consider using the naming convention of Scheme (and Lisp). Eg. instead of list_of_names_of_functions it should be named list-of-names-of-functions
The simple and immediate fix is to use (define list_of_functions (list+ - *)), then with (define sum (car list_of_functions)) it will work.
(edit:) This happens because list is a function which evaluates its argument(s) and returns the results in a list. Whereas quote (or ' in front of an expression) prevents its argument from being evaluated.
'(A B ...) is equivalent to (quote (A B ...)); that (A B ...) thing is a list of symbols, and quote preserves it as such.
It is a list of symbols because this is how Lisp code is read, either from a source file or from the REPL, i.e. at the interpreter's prompt. Other languages have their code as strings in a source code file, and compiler is some external magic which lives and works completely outside of the language. In Lisp-like languages, code is data. Code is read from textual source code file as (i.e. strings are turned into) nested lists of symbols, and explicit eval, as well as implicit evaluation, is deep inside the language itself.
Thus what you had is equivalent to the list
(define list_of_names (list '+ '- '*))
which contains unevaluated symbols, as opposed to the list
(define list_of_functions (list + - *))
which contains their values, which happen to be the usual built-in functions denoted by those "names".
And we can call a function, but we can't call a symbol (not in Scheme anyway).
As I mentioned in a comment, using eval is not the right answer to this: it 'works' but it opens the way to horrors.
If you have a symbol like + and you want to get its dynamic value then the Racket approach to doing this is to use namespaces. A namespace is really a machine which turns symbols into values in the same way that eval does, but that's all it does, unlike eval. Unfortunately I don't understand namespaces very well, but this will work:
(define-namespace-anchor nsa)
(define ns (namespace-anchor->namespace nsa))
(define (module-symbol-value s (in ns))
(namespace-variable-value s #t #f in))
Then
(define function-names '(+ - / *))
(define sum (module-symbol-value (first function-names)))
And now
> (sum 1 2 3)
6
> (eq? sum +)
#t
>
The problem with this approach is that it's leaky: if you have something like this:
(module msv racket
(provide module-symbol-value)
(define-namespace-anchor nsa)
(define ns (namespace-anchor->namespace nsa))
(define secret "secret")
(define (module-symbol-value s (in ns))
(namespace-variable-value s #t #f in)))
(require 'msv)
(define oops (module-symbol-value 'secret))
Now oops is secret. A way around this is to use make-base-namespace to get a namespace which is equivalent to racket/base.
I have just found the answer, sorry.
Solution will be to use the "eval" function
(define list_of_names_of_functions '(+ - *))
(define sum (car list_of_names_of_functions))
((eval sum) 2 3)
Are two Common Lisp function objects with the same symbol designator always eq? For example, this comparison seems to work:
(defun foo (fn)
(let ((ht (make-hash-table)))
(eq (symbol-function (hash-table-test ht)) fn)))
FOO
* (foo #'eql)
T
*(foo #'equal)
NIL
But this may rely on implementations not making latent copies of functions, presumably for reasons of efficiency. Since hash-table-test returns a symbol designator, the other (possibly better) eq alternative would be to derive the symbol from the function object? Is one approach better than the other?
Are two Common Lisp function objects with the same symbol designator always eq?
In Common Lisp a function is a piece of code, be it compiled or not. From the Glossary:
function n. 1. an object representing code, which can be called with zero or more arguments, and which produces zero or more values. 2. an object of type function.
A function designator, on the other hand, can be a symbol:
function designator n. a designator for a function; that is, an object that denotes a function and that is one of: a symbol (denoting the function named by that symbol in the global environment), or a function (denoting itself).
So, a symbol which is a function designator is something that, when evaluated in a certain context, or with a certain syntax like #'symbol or (function symbol), produces a function, and the comparison of two function designators is a comparison of the functions that they denote:
CL-USER> (eql #'car #'cdr)
NIL
CL-USER> (eql #'car (symbol-function 'car))
T
But note that this equality test is just a comparison of the identity of the functional objects (the pieces of code), like in:
CL-USER> (eq #'car #'car)
T
CL-USER> (let ((a (lambda (x) (1+ x))))
(eq a a))
T
but not of the actual bytes that represent them (the code!):
CL-USER> (let ((a (lambda (x) (car x)))
(eq a #'car))
NIL
CL-USER> (defun f (x) (1+ x))
F
CL-USER> (defun g (x) (1+ x))
G
CL-USER> (equalp (function f) (function g))
NIL
CL-USER> (equalp (lambda (x) (1+ x)) (lambda (x) (1+ x)))
NIL
Note that, in all these cases, the two functions compared have not only the same “meaning”, but in most cases the same “source code”, are compiled in the same way, and behaves identically on the same input data. This is because a function is mathematically a (possibly) infinite set of pairs (input, output) and one cannot compare infinte objects.
But this may rely on implementations not making latent copies of functions, presumably for reasons of efficiency.
There is no way for the user to copy a function (neither the system has any reason to perform a copy of a piece of code!), so any function is equal to itself in the same way as any pointer is equal only to itself.
Since hash-table-test returns a symbol designator, the other (possibly better) eq alternative would be to derive the symbol from the function object? Is one approach better than the other?
(I suppose you intend function designator, instead of symbol designator)
Actually, hash-table-test normally returns a function designator only as a symbol, as said in the manual:
test---a function designator. For the four standardized hash table test functions (see make-hash-table), the test value returned is always a symbol. If an implementation permits additional tests, it is implementation-dependent whether such tests are returned as function objects or function names.
So:
CL-USER> (type-of (hash-table-test (make-hash-table)))
SYMBOL
CL-USER> (eq 'eql (hash-table-test (make-hash-table)))
T
CL-USER> (eq #'eql (hash-table-test (make-hash-table)))
NIL
Note that in the last case we are comparing a function (the value of #'eql) with a symbol (what is returned by hash-table-test) and obviously this comparison returns a false value.
In conclusion:
It is not very reasonable to compare functions, unless you want to know if two functions are in effect the same object in memory (for istance if the two things are the same compiled code).
It is always important to distinguish functions from their designations as symbols (function names) or lists, like (LAMBDA parameters body), and decide what we want to actually compare.
#'eql is equivalent to (function eql). Unless there's a lexical function binding of eql, this is defined to return the global function definition of the symbol eql. That's also what (symbol-function 'eql) is defined to return.
So for any globally defined function f that isn't shadowed by a lexical definition,
(eq #'f (symbol-function 'f))
should always be true.
I have the following Common Lisp Function:
(defun test(A &rest indexes)
(if (null (first indexes))
A
(test (nth (+ 1 (first indexes)) A) (rest indexes))
)
)
As far as I know &rest parameters are treated as a list in the function body but since
(rest indexes) also returns a list I'm stuck with nested Lists as parameters.
For example (test '("a" "b" "c" ("d" "e")) 3 1 6 7)
would cause indexes to be ((1 6 7)) at the second call.
Is there any way to pass my list without having this problem?
Basic style rule: don't use &rest arguments for list processing functions.
Why? Common Lisp implementations are allowed to only support up to the value of CALL-ARGUMENTS-LIMIT number of arguments. This number is 50 or larger, depending on implementation.
This means your function might in some implementation process lists not larger as fifty items.
Better: pass the list as a separate argument.
(defun test (A indexes)
...)
(test '("a" "b" "c" ("d" "e")) '(3 1 6 7))
Wrong solution: don't use apply, since it does not solve the problem of limited argument lists.
CLISP
[1]> call-arguments-limit
4096
[2]> (defun l1 (&rest l) l)
L1
[3]> (apply #'l1 (loop repeat 5000 collect 1))
*** - APPLY: too many arguments given to
#<FUNCTION L1 (&REST L)
(DECLARE (SYSTEM::IN-DEFUN L1))
(BLOCK L1 L)>
The following restarts are available:
ABORT :R1 Abort main loop
rest is a accessor function that is paired together with first to give you the first element and the rest of the list. rest is the same as cdr.
&rest is a lambda list keyword that slurps the remaining arguments in the variable name that follows it.
You are really looking for apply. Imagine I make a function that can take 0 or more numeric parameters and add them together:
(defun add (&rest numbers)
(apply #'+ numbers))
Apply can take more than two arguments. The first is the function to call and all but the last are extra arguments that are put in front of the last arguments element. You are guaranteed the implementation supports 50 arguments or upto the number of arguments a function can take in that particular implementation supports above 50.
(apply #'+ 1 2 '(3 4 5)) ; ==> 15
Now recursing by &rest and apply makes inefficient code so you should use higher order functions, loop macro, or make a helper:
;; higher order function
(defun fetch-indexes (a &rest indexes)
(mapcar (lambda (i) (nth i a)) indexes))
;; loop macro
(defun fetch-indexes (a &rest indexes)
(loop :for i :in indexes
:collect (nth i a)))
;; helper function
(defun fetch-indexes (a &rest indexes)
(labels ((helper (indexes)
(if (endp indexes)
'()
(cons (nth (first indexes) a)
(helper (rest indexes))))))
(helper indexes)))
;; test (works the same with all)
(fetch-indexes '(a b c d) 2 3 0 1)
; ==> (c d a b)
Using apply in recursion should be avoided, but I'll show how it's done.
(defun fetch-indexes (a &rest indexes)
(if (endp indexes)
'()
(cons (nth (first indexes) a)
(apply #'fetch-indexes a (rest indexes)))))
In your example you have nested lists. In order for that to work you would need to flatten it as well. I haven't done that so these supports one proper list of elements.
Another solution, albeit a bit more verbose, but less reliant on details of apply is to use a sub-function for the recursion, which just takes a list. The outer "main" entry point takes the &rest indices syntax, while the inner function takes it as a list:
(defun test (a &rest indices)
(labels ((internal-test (indices)
;; ... the recursion thing calling internal-test
))
(internal-test indices)))
In contrast to the (defun add (&rest args) ... ) example, you might still have some arguments before the rest, which in case of using apply would require you to append those to the variable arguments list.
Of course, as Rainer Joswig pointed out, you need to take care only to use this, when the number of variable args is small.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to interpret what this scheme function does:
(define (y s lis)
(cond
((null? lis) '() )
((equal? s (car lis)) lis)
(else (y s (cdr lis)))))
It runs but I am not exactly sure what it is doing or trying to do.
Does it need a list to sort or something? I am using DrRacket to run it. I have never seen scheme before
and any help would be greatly appreciated.
It's a search function, that given a value and a list looks for the value in the list. If it finds it, returns the part of the list starting at the point where the element was found. If the value isn't in the list, it returns an empty list. Let's see how this works, step by step:
; define a function called `y` that receives
; as parameters a value `s` and a list `lis`
(define (y s lis)
; we're going to test three possible conditions
(cond
; if the list is empty
((null? lis)
; then we didn't find the value, return the empty list
'())
; if the first element in the list equals the `s` value
((equal? s (car lis))
; then return the list up to this point
lis)
; otherwise
(else
; keep looking in the rest of the list, by recurring over it
(y s (cdr lis)))))
To see the function in action, let's test it with some values:
; call the function with a value that is present in the list
(y 3 '(1 2 3 4 5))
; see how the list is returned starting at the point where the value was found
=> '(3 4 5)
; call the function with a value that is not present in the list
(y 7 '(1 2 3 4 5))
; an empty list is returned
=> '()
To really, really understand how this works, you have to realize that in the last line of the function we're calling the function itself - it's the magic of recursion! Also, it'll help you to understand what each one of the primitive operations used is doing, click on each link to read the documentation, I'm simplifying and summarizing the key points:
define: give a name to a value (in particular, it can be a function)
cond: test for different conditions, execute some expressions depending on which condition was true
null?: test to see if a list is empty
equal?: compare two objects for equality
car: get the first element in a list
cdr: get the rest of the elements in a list
We can go on a mystic journey and treat this definition as it is, a definition. Cryptic? This means equational reasoning, i.e. reasoning through equations, i.e. definitions. Here's what I mean. You have
(define (y s lis)
(cond
((null? lis) '() )
((equal? s (car lis)) lis)
(else (y s (cdr lis)))))
We can re-write this as two equations,
y s lis = lis , if (null? lis) || (equal? s (car lis))
= y s (cdr lis) , otherwise
Here y s lis stands for "the result of Scheme call (y s lis)" and so on.
Clearly we have two cases. One is base case, another describes a reduction step. Re-writing again,
y s lis = y s (cdr lis) , if (not (null? lis)) && (not (equal? s (car lis)))
= lis , otherwise
This is practically in English now. So while lis is not null, and its car isn't s, we proceed along to its cdr, and so on and so forth until either we hit the list's end, or its car is s, and then we stop. So when we've found s, we return the list, otherwise the list is exhausted and the empty list is returned. This is otherwise known as member in Common Lisp. R5RS Scheme's member, as well as Racket's, returns #f when no x is found in the list.
Where is the equational reasoning here, you ask? In treating the RHS as the answer, and re-applying the same set of rules for each reduction step. For example:
y x [a,b,x,c,d,e] ; A
= y x [b,x,c,d,e] ; by 1st rule ; B
= y x [x,c,d,e] ; by 1st rule ; C
= [x,c,d,e] ; by 2nd rule ; D
When we get to apply the 2nd rule, we arrive at the end of the reduction chain, i.e. we get our answer. The result of the Scheme call corresponding to A will be the same as the Scheme call's corresponding to B, or C, or finally D:
(y x (cons a (cons b (cons x z)))) ==
(y x (cons b (cons x z))) ==
(y x (cons x z)) ==
(cons x z)
What's so mystic about it, you ask? Here probably not much; but usually what that means is that by assuming the meaning of a function, and by interpreting the RHS through it, we arrive at the meaning of the LHS; and if this is the same meaning, that is our proof for it. Induction is kind of magical. For more involved examples see How to recursively reverse a list using only basic operations?.
Incidentally structural recursion is also known as folding, so your function is really
y s lis = para (λ (xs x r) (if (equal? x s) xs (r))) '() lis
using one type of folding, paramorphism, with explicit laziness,
para f z lis = g lis
where
g xs = z , if (null? xs)
= f xs (car xs) (λ () (g (cdr xs))) , otherwise
Looks like homework.
Since you are using DrRacket you should add
(y 'e '(q w e r t y))
And hit Debug Q >| and step through it. A different way to write the same code is:
(define (y s lis)
(if (null? lis)
'()
(if (equal? s (car lis))
lis
(y s (cdr lis)))))
Or you can choose Intermediate student with lambda from the language menu in the bottom left and then press Step >|.
That language doesn't support all of Scheme but a small subset, including everything in this procedure. It's great to see how things are evaluated.
I think its a test to see if element s is found inside the list lst. I'm still learning Scheme (but I did get through The Little Schemer so let me try (this has likely been typed and submitted before I I finish this but I'll try anyways).
So define is creating a function called y that takes the arguments s and lst. The first line of this function is cond which goes though each list and tries to find some expression that evaluates to true. The first condition is the exit condition (always have an exit when you iterate) it checks to see if lis is null, if so it returns a quoted empty list (like the null of lists)
The next condition looks to see if the first element of lst (car takes the first element of a list) equals s if so then it returns the rest f the list (this means it found the element).
The last condition is else which is alway true and it calls the function y with the same s and the list minus the first element (cdr returns a sublist of the list minus the first element). Hope this helps (and I hope I was right)
Here is an example of calling this function:
(y 'b (list 'a 'b 'c))
And this returns
('b 'c)
I am having trouble writing a tail-recursive power function in scheme. I want to write the function using a helper function. I know that I need to have a parameter to hold an accumulated value, but I am stuck after that. My code is as follows.
(define (pow-tr a b)
(define (pow-tr-h result)
(if (= b 0)
result
pow-tr a (- b 1))(* result a)) pow-tr-h 1)
I edited my code, and now it works. It is as follows:
(define (pow-tr2 a b)
(define (pow-tr2-h a b result)
(if (= 0 b)
result
(pow-tr2-h a (- b 1) (* result a))))
(pow-tr2-h a b 1))
Can someone explain to me why the helper function should have the same parameters as the main function. I am having a hard time trying to think of why this is necessary.
It's not correct to state that "the helper function should have the same parameters as the main function". You only need to pass the parameters that are going to change in each iteration - in the example, the exponent and the accumulated result. For instance, this will work fine without passing the base as a parameter:
(define (pow-tr2 a b)
(define (pow-tr2-h b result)
(if (= b 0)
result
(pow-tr2-h (- b 1) (* result a))))
(pow-tr2-h b 1))
It works because the inner, helper procedure can "see" the a parameter defined in the outer, main procedure. And because the base is never going to change, we don't have to pass it around. To read more about this, take a look at the section titled "Internal definitions and block structure" in the wonderful SICP book.
Now that you're using helper procedures, it'd be a good idea to start using named let, a very handy syntax for writing helpers without explicitly coding an inner procedure. The above code is equivalent to this:
(define (pow-tr2 a b)
(let pow-tr2-h [(b b) (result 1)]
(if (= b 0)
result
(pow-tr2-h (- b 1) (* result a)))))
Even though it has the same name, it's not the same parameter. If you dug into what the interpreter is doing you'll see "a" defined twice. Once for the local scope, but it still remembers the "a" on the outer scope. When the interpreter invokes a function it tries to bind the values of the arguments to the formal parameters.
The reason that you pass the values through rather mutating state like you would likely do in an algol family language is that by not mutating state you can use a substitution model to reason about the behaviour of procedures. That same procedure called at anytime with arguments will yeild the same result as it is called from anywhere else with the same arguments.
In a purely functional style values never change, rather you keep calling the function with new values. The compiler should be able to write code in a tight loop that updates the values in place on the stack (tail call elimination). This way you can worry more about the correctness of the algorithm rather than acting as a human compiler, which truth be told is a very inefficient machine-task pairing.
(define (power a b)
(if (zero? b)
1
(* a (power a (- b 1)))))
(display (power 3.5 3))