Is there an ignore function in Racket? - function

In other words, does there exist a function f such that f x does not evaluate x and just returns void? I tried to implement something similar by using (define (ignore x) (if true void x)) but it still evaluates x.

You can also use
(when #f x)
which does not require a macro definition. This has the advantage that someone reading your code does not have to look at the definition of your macro.
Racket has the #; reader macro to comment out expressions; consider whether this might make sense. For instance,
> (+ 1 2 #;3 4)
7

Related

Please could you explain to me how currying works when it comes to higher order functions, particularly the example below

Can someone please help me with the below,
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
I do not understand how the above works. If we had something like (+3) 10 surely it would produce 13? How is that f (f x). Basically I do not understand currying when it comes to looking at higher order functions.
So what I'm not understanding is if say we had a function of the form a -> a -> a it would take an input a then produce a function which expects another input a to produce an output. So if we had add 5 3 then doing add 5 would produce a function which would expect the input 3 to produce a final output of 8. My question is how does that work here. We take a function in as an input so does partial function application work here like it did in add x y or am I completely overcomplicating everything?
That's not currying, that's partial application.
> :t (+)
(+) :: Num a => a -> a -> a
> :t (+) 3
(+) 3 :: Num a => a -> a
The partial application (+) 3 indeed produces a function (+3)(*) which awaits another numerical input to produce its result. And it does so, whether once or twice.
You example is expanded as
applyTwice (+3) 10 = (+3) ((+3) 10)
= (+3) (10+3)
= (10+3)+3
That's all there is to it.
(*)(actually, it's (3 +), but that's the same as (+ 3) anyway).
As chepner clarifies in the comments (quoted with minimal copy editing),
partial application is an illusion created by the fact that functions only take one argument, and the combination of the right associativity of (->) and the left associativity of function application. (+) 3 isn't really a partial application. It's just [a regular] application of (+) to an argument 3.
So seen from the point of view of other, more traditional languages, we refer to this as a distinction between currying and partial application.
But seen from the Haskell perspective it is all indeed about currying, i.e. applying a function to its arguments one at a time, until fully saturated as indicated by its type (i.e. a->a->a value applied to an a value becomes an a->a value, and that then becomes an a value when applied to an a value in its turn).

racket - how to use the elements of a list as a procedure (function)

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)

Tail-Recursive Power Function in Scheme

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))

What is the advantage of a symbol that binds to a value and function at the same time?

In lisp, a symbol can be bound to both a value and a function at the same time.
For example,
Symbol f bound to a function
(defun f(x)
(* 2 x))
Symbol f bound to a value
(setq f 10)
So i write something like this:
(f f)
=> 20
What is the benefit of such a feature?
The symbol can have both a function and a value. The function can be retrieved with SYMBOL-FUNCTION and the value with SYMBOL-VALUE.
This is not the complete view. Common Lisp has (at least) two namespaces, one for functions and one for variables. Global symbols participate in this. But for local functions the symbols are not involved.
So what are the advantages:
no name clashes between identifiers for functions and variables.
Scheme: (define (foo lst) (list lst))
CL: (defun foo (list) (list list))
no runtime checks whether something is really a function
Scheme: (define (foo) (bar))
CL: (defun foo () (bar))
In Scheme it is not clear what BAR is. It could be a number and that would lead to a runtime error when calling FOO.
In CL BAR is either a function or undefined. It can never be anything else. It can for example never be a number. It is not possible to bind a function name to a number, thus this case never needs to be checked at runtime.
It's useful for everyday tasks, but the main reason is because of macros, you'll understand why once you study it.

In common-lisp, how do I modify part of a list parameter from within a function without changing the original list?

I'm trying to pass a list to a function in Lisp, and change the contents of that list within the function without affecting the original list. I've read that Lisp is pass-by-value, and it's true, but there is something else going on that I don't quite understand. For example, this code works as expected:
(defun test ()
(setf original '(a b c))
(modify original)
(print original))
(defun modify (n)
(setf n '(x y z))
n)
If you call (test), it prints (a b c) even though (modify) returns (x y z).
However, it doesn't work that way if you try to change just part of the list. I assume this has something to do with lists that have the same content being the same in memory everywhere or something like that? Here is an example:
(defun test ()
(setf original '(a b c))
(modify original)
(print original))
(defun modify (n)
(setf (first n) 'x)
n)
Then (test) prints (x b c). So how do I change some elements of a list parameter in a function, as if that list was local to that function?
Lisp lists are based on cons cells. Variables are like pointers to cons cells (or other Lisp objects). Changing a variable will not change other variables. Changing cons cells will be visible in all places where there are references to those cons cells.
A good book is Touretzky, Common Lisp: A Gentle Introduction to Symbolic Computation.
There is also software that draws trees of lists and cons cells.
If you pass a list to a function like this:
(modify (list 1 2 3))
Then you have three different ways to use the list:
destructive modification of cons cells
(defun modify (list)
(setf (first list) 'foo)) ; This sets the CAR of the first cons cell to 'foo .
structure sharing
(defun modify (list)
(cons 'bar (rest list)))
Above returns a list that shares structure with the passed in list: the rest elements are the same in both lists.
copying
(defun modify (list)
(cons 'baz (copy-list (rest list))))
Above function BAZ is similar to BAR, but no list cells are shared, since the list is copied.
Needless to say that destructive modification often should be avoided, unless there is a real reason to do it (like saving memory when it is worth it).
Notes:
never destructively modify literal constant lists
Dont' do: (let ((l '(a b c))) (setf (first l) 'bar))
Reason: the list may be write protected, or may be shared with other lists (arranged by the compiler), etc.
Also:
Introduce variables
like this
(let ((original (list 'a 'b 'c)))
(setf (first original) 'bar))
or like this
(defun foo (original-list)
(setf (first original-list) 'bar))
never SETF an undefined variable.
SETF modifies a place. n can be a place. The first element of the list n points to can also be a place.
In both cases, the list held by original is passed to modify as its parameter n. This means that both original in the function test and n in the function modify now hold the same list, which means that both original and n now point to its first element.
After SETF modifies n in the first case, it no longer points to that list but to a new list. The list pointed to by original is unaffected. The new list is then returned by modify, but since this value is not assigned to anything, it fades out of existence and will soon be garbage collected.
In the second case, SETF modifies not n, but the first element of the list n points to. This is the same list original points to, so, afterwards, you can see the modified list also through this variable.
In order to copy a list, use COPY-LIST.
it's nearly the same as this example in C:
void modify1(char *p) {
p = "hi";
}
void modify2(char *p) {
p[0] = 'h';
}
in both cases a pointer is passed, if you change the pointer, you're changing the parameter copy of the pointer value (that it's on the stack), if you change the contents, you're changing the value of whatever object was pointed.
You probably have problems because even though Lisp is pass-by-value references to objects are passed, like in Java or Python. Your cons cells contain references which you modify, so you modify both original and local one.
IMO, you should try to write functions in a more functional style to avoid such problems. Even though Common Lisp is multi-paradigm a functional style is a more appropriate way.
(defun modify (n)
(cons 'x (cdr n))