How to create tail recursive reverse list procedure? - function

This is similar question to this one How to Reverse a List? but for iterative (tail recursive) function. How can I create such function? Is it possible?

or even more explicit:
(define (reverse xs)
(let loop ((pend xs)
(res '()))
(if (null? pend)
res
(loop (cdr pend) (cons (car pend) res)))))
The fold answer by Chris is more neat and can be better wrt performance (for various reasons).
As of second part of your question it is always possible, i.e. every function can be made tail-recursive (e.g. by transforming to cps, which can be done mechanically).

Yes; in fact the standard implementation of reverse is totally tail-recursive.
(define (reverse xs)
(fold cons '() xs))
Don't like using fold? No problem:
(define (reverse xs)
(do ((result '() (cons (car xs) result))
(xs xs (cdr xs)))
((null? xs) result)))

Related

Combining two functions in LISP to atomize list and then find max?

So, id like to take in a list of numbers, atomize it (to remove nested integers), then find the max value. I have two functions written that accomplish this individually, but can't figure out how to combine them in LISP so I can make one call and have them both run. Any help would be appreciated.
:Atomize function to remove nests
:(atomify ‘( a (b c) (e (f (g h) i)) j)->(a b c e f g h i j)
(defun atomify (numbers)
(cond ((null numbers) nil)
((atom (car numbers))
(cons (car numbers)
(atomify (cdr numbers))))
(t
(append (atomify (car numbers))
(atomify (cdr numbers))))))
:Max value of a list of integers function
(defun large_atom (numbers)
(if (null numbers)
0
(max (first numbers)
(large_atom (rest numbers)))))
Jamie. Your way has two steps:
1. Flatten list
2. Find max value from result of 1'st step
In this case it's true way. But you need do it with one function call. It's easy. Just use labels, apply and of course max
(defun foo (lst)
(labels ((flatten (lst acc)
(cond
((null lst)
acc)
((consp (car lst))
(flatten (cdr lst) (flatten (car lst) acc)))
(t
(flatten (cdr lst) (cons (car lst) acc))))))
(apply #'max (flatten lst nil))))
Another way, is do not flatten source list. But in this case you need find first value to compare with other values. Try it yourself.
Here is another way to solve the problem: rather than flattening the list, this walks down it recursively. This is very explicit about what the structure of the list must be: a good list is a non-null proper list each of whose elements is either an integer or a good list.
The problem with this approach is that it's not tail recursive so it will necessarily fail on very large structures (and even if it was tail recursive CL does not promise to deal with tail recursion.
(defun greatest-integer (good-list)
;; a good list is one of:
;; - a cons of a good list and either a good list or ()
;; - a cons of an integer and either a good list or ()
;; In particular it can't be () and it can't be an improper list
;;
(destructuring-bind (a . b) good-list
;; a can be an integer or a good list, b can be null or a good list
(etypecase b
(null
(etypecase a
(integer a)
(cons (greatest-integer a))))
(cons
(max (etypecase a
(integer a)
(cons (greatest-integer a)))
(greatest-integer b))))))

How to recreate apply in scheme

how would i create the function apply in scheme?
A my-apply function that does the same thing as it.
(define (my-apply fn lst)
(if (null? lst)
I'm not sure where to go from here or how to start.
I think apply is "more fundamental" than eval, so the following is cheating:
(define (my-apply func args)
(eval `(,func ,#args)))
I don't think you can do it without eval.
I created a lisp interpreter a while back and it has eval and macros, but it didn't have apply. I wondered if there was a way I could make my interpreter support apply so made an effort to try this. Here is my first attempt:
(define (my-apply proc args)
(eval (cons proc args)))
This clearly doesn't work since the function and the list of arguments gets evaluated twice. eg. (my-apply cons '(a b)) will give you (cons a b) and not (cons 'a 'b). I then thought that this might be a job for a macro but threw the idea away since the list of arguments are not known at macro expansion time. Procedure it needs to be so I though I could quote the list before I pass it to eval.
(define (my-apply proc args)
(define (q v)
(list 'quote v))
(eval (cons proc (map q args))))
This actually works, but this does a lot more work than a native apply would do to undo the job eval does.
If you are not allowed to use eval you are truely out of luck. It cannot be done. The same goes for implementing eval without using apply since then you have no way of doing primitives.
(define (my-two-arg-apply f a)
(let ((l (length a)))
(cond ((= l 0) (f))
((= l 1) (f (car a)))
((= l 2) (f (car a) (cadr a))
...
((= l 5) (f (car a) (cadr a) ... (caddddr a)))
...
((= l 7) (f (car a) (cadr a) ... (caddddr a)
(list-ref a 5) (list-ref a 6)))
... ;; lots more cases
(else (error "argument passing limit exceeded")))))
A macro could be used to generate the large quantity of code needed.
error was introduced in R6RS. Amazingly, Scheme programs had no reasonable way to report errors before that.
Don't even think about making a pop macro and using the pattern (f (pop a) (pop a) ... (pop a)); Scheme doesn't have a defined evaluation order for function arguments unlike some other Lisp dialects like ANSI CL.

Combining two functions in Scheme

I have the filter-function and the reverse-function done out in my own code
(define reverse_
(lambda (xs)
(if (null? xs)
xs
(append (reverse_ (cdr xs))
(list (car xs))))))
and
(define filter_
(lambda (p? xs)
(if (null? xs)
xs
(append (if (p? (car xs))
(list (car xs))
(list))
(filter_ p? (cdr xs))))))
I want to combine the two functions into the (reverse-filter) function i.e you could type (reverse-filter symbol? '(1 2 3 a b c)) and it would return -> c b a.
It works now by simply typing (reverse_ (filter_ symbol? '(1 2 3 a b c))) -> c b a but I just want to combine the two.
Any help on doing this in the general case and in this specific one would be much appreciated
For the general case, we can use the curry and compose procedures (which hopefully are available in your interpreter), they allow us to manipulate other procedures:
((compose (curry filter_ symbol?) reverse_)
'(1 2 3 a b c))
=> '(c b a)
For illustrative purposes, here's a naive implementation of both procedures, to understand what they're doing under the hood:
(define (curry f x)
(lambda (y) (f x y)))
(define (compose f g)
(lambda (x) (f (g x))))
compose is the right and lazy thing to do, however since lists are iterated from head to tail but created from tail to head creating the reverse result is actually more efficient when done in one go:
(define (reverse-filter p? xs)
(define (helper lst acc)
(if (null? lst)
acc
(helper (cdr lst)
(let ((a (car lst)))
(if (p? a)
(cons a acc)
acc)))))
(helper xs '()))
(reverse-filter symbol? '(1 2 3 a b c))
; ==> (c b a)

"Adding" two functions together in Scheme

I am going through a practice exam for my programming languages course. One of the problems states:
Define a function named function+ that “adds” two functions together and returns this composition. For example:
((function+ cube double) 3)
should evaluate to 216, assuming reasonable implementations of the functions cube and double.
I am not sure how to approach this problem. I believe you are supposed to use the functionality of lambdas, but I am not entirely sure.
If you need a procedure which allows you two compose to unary procedures (procedure with only 1 parameter), you'll smack yourself in the head after seeing how simple the implementation is
(define (function+ f g)
(λ (x) (f (g x))))
(define (cube x)
(* x x x))
(define (double x)
(+ x x))
((function+ cube double) 3)
;=> 216
Basically if you need to do that you just do (x (y args ...)) so if you need to have a procedure that takes two arguments proc1 and proc2 returns a lambda that takes any number of arguments. You just use apply to give proc1 arguments as a list and pass the result to proc2. It would look something like this:
(define (compose-two proc2 proc1)
(lambda args
...))
The general compose is slightly more complicated as it takes any number of arguments:
#!r6rs
(import (rnrs))
(define my-compose
(let* ((apply-1
(lambda (proc value)
(proc value)))
(gen
(lambda (procs)
(let ((initial (car procs))
(additional (cdr procs)))
(lambda args
(fold-left apply-1
(apply initial args)
additional))))))
(lambda procs
(cond ((null? procs) values)
((null? (cdr procs)) (car procs))
(else (gen (reverse procs)))))))
(define (add1 x) (+ x 1))
((my-compose) 1) ;==> 1
((my-compose +) 1 2 3) ; ==> 6
((my-compose sqrt add1 +) 9 15) ; ==> 5

Creating a Function that produces a Function Scheme/DrRacket

I'm working on a function that takes in a list of structures and then using that list of structures produces a function that processes a list of symbols into a number. Each structure is made up of a symbol, that will be in the second list consumed, and a number. This function produced has to turn the list of symbols into a number by assigning each symbol a value based on the previous structures. Using abstract list functions btw.
Example: ((function (list (make-value 'value1 10) (make-value 'value2 20)))
(list 'value1 'value2 'nothing 'value1)) would produced 40.
Heres my code but it only works for specific cases.
(define (function lst)
(lambda (x) (foldr + 0 (map (lambda (x)
(cond
[(equal? x (value-name(first lst)))(value-value (first lst))]
[else (value-value (second lst))]))
(filter (lambda (x) (member? x (map value-name lst)))x)))))
Looks like a homework. Basic shape of your solution is ok. I think the reason you have a problem here is that there is no decomposition in your code so it's easy to get lost in parentheses.
Let's start with your idea of fold-ing with + over list of integers as a last step of computation.
For this subtask you have:
1) a list of (name, value) pairs
2) a list of names
and you need to get a list of values. Write a separate function which does exactly that and use it. Like this
(define (function lst)
(lambda (x) (foldr +
0
(to-values x lst)))
(define (to-values names names-to-values)
(map (lambda (name)
(to-value name names-to-values))))
(define (to-value n ns-to-vs)
...)
Here we map over the names with another little function. It will lookup the n value in ns-to-vs and return it or 0 if there is no one.
There are two approaches for solving the problem with foldr, it'd be interesting to study and understand both of them. The first one, attempted in the question, is to first produce a list with all the values and let foldr take care of adding them. It can be implemented in a simpler way like this:
(define (function lst)
(lambda (x)
(foldr +
0
(map (lambda (e)
(cond ((assoc e lst) => value-value)
(else 0)))
x))))
Alternatively: maybe using foldr is overkill, applying + is simpler:
(define (function lst)
(lambda (x)
(apply +
(map (lambda (e)
(cond ((assoc e lst) => value-value)
(else 0)))
x))))
In the second approach we take the input list "as is" and let foldr's lambda perform the addition logic. This is more efficient than the first approach using foldr, because there's no need to create an intermediate list - the one generated by map in the first version:
(define (function lst)
(lambda (x)
(foldr (lambda (e a)
(cond ((assoc e lst) => (lambda (p) (+ a (value-value p))))
(else a)))
0
x)))
In both approaches I'm using assoc for finding the element in the list; it's easy to implement as a helper function if you're not allowed to use it or if it doesn't work for the values created with make-value: assoc takes a list of name-value pairs and returns the first pair with the given name. The => syntax of cond passes the pair returned by assoc to a lambda's parameter and executes it.
And because you're using Racket, there's a bit of syntactic sugar that can be used for returning a function from another function, try this equivalent code, for simplicity's sake:
(define ((function lst) x)
(foldr +
0
(map (lambda (e)
(cond ((assoc e lst) => value-value)
(else 0)))
x)))
Or this:
(define ((function lst) x)
(foldr (lambda (e a)
(cond ((assoc e lst) => (lambda (p) (+ a (value-value p))))
(else a)))
0
x))
Anyway, the result is as expected:
((function (list (make-value 'value1 10) (make-value 'value2 20)))
(list 'value1 'value2 'nothing 'value1))
=> 40