Primitives and built-in functions in Racket - lisp

Are primitives and built-in functions the same thing in Racket?
If no, what's the difference between them?

The short answer is no!
A primitive function are those which aren't implemented in its own runtime but inherently implemented by the runtime. eg. cons is implemented in C and the racket VM comes with the code that implements it. list* too, but it didn't really need to be a primitive. Some primitives are so just to speed things up.
Built in functions just means they come with the language. These are all primitives and all the standard library that is implemented in the language itself and is shipped with the implementation. An example is make-list. If you rigth click in the IDE and choose "Open defining file" you'll see it's implementation in racket:
(define (make-list n x)
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'make-list "exact-nonnegative-integer?" n))
(let loop ([n n] [r '()])
(if (zero? n) r (loop (sub1 n) (cons x r)))))
An example of function that are neither primitive nor built in would be many of the packages in pkgs.racket-lang.org.

Related

Meaning of graphical question-mark on reference hover in DrRacket?

In the DrRacket GUI, hovering the mouse over a symbol often produces a graphical line between the symbol and other uses of the symbol in the file or a line from the symbol to an import origin for that symbol. Sometimes (but not always), the graphical line is accompanied by a graphical question mark (not a text question mark) as in the illustration below (look very carefully at the bottom of the line; the question mark is in dark purple on a black background, so it's quite hard to see, but it /is/ there). What is the meaning of that question mark?
DrRacket draws a blue arrow (no question mark) between a binding (definition, local binding, import, etc) and a reference to that binding.
It draws a purple arrow with a question mark between a binding and a possible reference within a syntax template. The question mark is a reminder that
that occurrence of the identifier might not be used as a reference
even if it is, it might refer to another binding
Here's a silly example:
#lang racket
(define-syntax-rule (define-undivider fname divisor)
(define (fname quotient remainder)
(println (list 'quotient quotient 'remainder remainder))
(+ (* divisor quotient) remainder)))
(define-undivider f 10)
(f 2 5) ;;=> 25
Some of the uses of quotient and remainder aren't references at all, because they occur inside of a quote expression. Others are references, but they refer to the function's arguments rather than the Racket functions. DrRacket can't tell that just by looking at the macro definition (and it's harder than you might think), so it marks the apparent binding relationship as a "maybe".

What's the difference between Program Fixpoint and Function in Coq?

They seem to serve similar purposes. The one difference I've noticed so far is that while Program Fixpoint will accept a compound measure like {measure (length l1 + length l2) }, Function seems to reject this and will only allow {measure length l1}.
Is Program Fixpoint strictly more powerful than Function, or are they better suited for different use cases?
This may not be a complete list, but it is what I have found so far:
As you already mentioned, Program Fixpoint allows the measure to look at more than one argument.
Function creates a foo_equation lemma that can be used to rewrite calls to foo with its RHS. Very useful to avoid problems like Coq simpl for Program Fixpoint.
In some (simple?) cases, Function can define a foo_ind lemma to perform induction along the structure of recursive calls of foo. Again, very useful to prove things about foo without effectively repeating the termination argument in the proof.
Program Fixpoint can be tricked into supporting nested recursion, see https://stackoverflow.com/a/46859452/946226. This is also why Program Fixpoint can define the Ackermann function when Function cannot.

Why does Octave/Matlab use function handles

What benefit does it get from treating functions specially? For example,
function n = f(x)
2*x
endfunction
f(2) //outputs 4
f = #f
f(2) //outputs 4
If handles can be called the same way as functions, then what benefit do we get from functions being treated specially. By specially I mean that variables referring to functions can't be passed as arguments:
function n = m(f,x)
f(x)
end
m(f,2) // generates error since f is called without arguments
Why aren't functions procedures (which are always pointed to by variables) like in other functional languages?
EDIT:
It seems like my question has been completely misunderstood, so I will rephrase it. Compare the following python code
def f(x):
return 2*x
def m(f,x):
return f(x)
m(f,3)
to the octave code
function n = f(x)
2*x
end
function n = m(f,x)
f(x)
end
m(#f,2) % note that we need the #
So my question then is, what exactly is a function "object" in octave? In python, it is simply a value (functions are primitive objects which can be assigned to variables). What benefit does octave/matlab get from treating functions differently from primitive objects like all other functional languages do?
What would the following variables point to (what does the internal structure look like?)
x = 2
function n = f(x)
2*x
end
g = #f
In python, you could simply assign g=f (without needing an indirection with #). Why does octave not also work this way? What do they get from treating functions specially (and not like a primitive value)?
Variables referring to functions can be passed as arguments in matlab. Create a file called func.m with the following code
function [ sqr ] = func( x )
sqr = x.^2;
end
Create a file called 'test.m' like this
function [ output ] = test( f, x )
output = f(x);
end
Now, try the following
f=#func;
output = test(f, 3);
There's no "why is it different". It's a design decision. That's just how matlab/octave works. Which is very similar to how, say, c works.
I do not have intricate knowledge of the inner workings of either, but presumably a function simply becomes a symbol which can be accessed at runtime and used to call the instructions specified in its definition (which could be either interpreted or precompiled instructions). A "function handle" on the other hand, is more comparable to a function pointer, which, just like c, can either be used to redirect to the function it's pointing to, or passed as an argument.
This allows matlab/octave to do stuff like define a function completely in its own file, and not require that file to be run / imported for the function to be loaded into memory. It just needs to be accessible (i.e. in the path), and when matlab/octave starts a new session, it will create the appropriate table of available functions / symbols that can be used in the session. Whereas with python, when you define a function in a file, you need to 'run' / import that file for the function definition to be loaded into memory, as a series of interpreted instructions in the REPL session itself. It's just a different way of doing things, and one isn't necessarily better than the other. They're just different design / implementation decisions. Both work very well.
As for whether matlab/octave is good for functional programming / designed with functional programming in mind, I would say that it would not be my language of choice for functional programming; you can do some interesting functional programming with it, but it was not the kind of programming that it was designed for; it was primarily designed with scientific programming in mind, and it excels at that.

Tidy up expression after differentiating

The equations I am working with in this problem contain exponentials. For this reason, after differentiating they appear again pretty much unchanged apart from additional constants and other factors. I was wondering if it might be possible to collect those exponentials back into the name of the expression they where part of. Here is an example:
Given this function definition
f:= x -> A*exp(B/x)
After differentiating, one would get
A*exp(B/x)*(-B/x^2)
And it would be great if I could somehow convert it to
f(x)*(-B/x^2)
Is this possible with MuPad or any other CAS package?
It's easy in MAPLE, use general substitution command algsubs
> f:= x -> A*exp(B/x)
> g := diff(f(x), x)
> algsubs(A*exp(B/x) = F, g)
For more complex expressions, try collect

Plotting data sequentially from emacs using Common Lisp and Gnuplot

Assume that I have some array of data (a vector to be specific).
Can I plot it element by element sequentially using Gnuplot such that it seems as if it is a real life signal that is being traced through a monitor?
I know that I can write the whole data into a text file using Common Lisp, then using gnuplot I can plot it in a batch format. What I require is that I want to put a point on my plot as data comes sequentially.
Data will probably be generated inside a loop, thus you may consider x-axis as the integer valued discrete-time axis. So in the loop if the first element of the array is generated as 5, I would like to put a point on my plot to (0,5). Then if the second element is generated as 3, I would like to put another point on my plot to (1,7) (preserving the old data point). So as I iterate through the loop, I plot the data sequentially.
I am using emacs and Common Lisp for my purposes and I want to plot this data staying within these tools. If there are any other options other than Gnuplot, I would like to hear them.
If this is not easily possible, it would be cool, if I can run a Gnuplot command file by some Common Lisp command.
edit:
Following advices people gave under this thread, I wrote a code using cgn which uses ltk.
Right now I open two x11 windows at pre-specified positions on my screen and I enter the loop. In loop each time I open a stream and write the data (sine and cosine waves of 0.25 Hz sampled at 20 Hz) to the text file trial.txt with the :if-exists :append option and close the stream. Then at each iteration I plot the whole data using the gnuplot through the format-gnuplot command. This code gives me two windows of pre-specified x and y ranges and then one can watch the evolutions of aforementioned sine and cosine waves in the windows.
As I have stated before I don't have strong programming background (I am an electrical engineer who somehow ended using common lisp) and I am pretty sure that my code is non-optimal and unelegant. If you guys have some further advices, corrections etc. I would really like to hear them. The code is here:
(setf filename "trial.txt")
(setf path (make-pathname :name filename))
(setf str (open path :direction :output :if-exists :supersede :if-does-not-exist :create))
(format str "~,4F ~,4F" -1 -1)
(close str)
;start gnuplot process
(start-gnuplot "/Applications/Gnuplot.app/Contents/Resources/bin/gnuplot")
;set 2 x11 windows with the following properties
(format-gnuplot "cd ~S" "Users/yberol/Desktop/lispbox/code")
(format-gnuplot "set terminal x11 0 position 0,0")
(format-gnuplot "set xrange [0:10]")
(format-gnuplot "set yrange [-1:1]")
(format-gnuplot "unset key")
(format-gnuplot "set grid")
(format-gnuplot "plot ~S using 1" filename)
(format-gnuplot "set terminal x11 1 position 800,0")
(format-gnuplot "plot ~S using 2" filename)
;write data into text
(loop :for i :from 0 :to 10 :by (/ 1 20) :do
(setf str (open path :direction :output :if-exists :append :if-does-not-exist :create))
(format str "~,4F ~,4F ~,4F ~%" i (sin (* 2 pi (/ 5 20) i)) (cos (* 2 pi (/ 5 20) i)))
(close str)
(format-gnuplot "set terminal x11 0")
(format-gnuplot "plot ~S using 1:2 with lines" filename)
(format-gnuplot "set terminal x11 1")
(format-gnuplot "plot ~S using 1:3 with lines" filename)
(sleep 0.1))
(close-gnuplot)
Thank you very much.
cgn is a working Common Lisp solution for interfacing with gnuplot, which uses LTK
You could create process to gnuplot and send data to it's stdin along with plotting commands. I'm not sure how to manage such process in Common Lisp but you definitely can do this in Emacs:
(setf *gnuplot-proc* (start-process "gnuplot" "*gnuplot-proc*" "gnuplot"))
;;; initiate plotting of data from stdin
(process-send-string *gnuplot-proc*
"plot \"-\" with lines\n")
;; send your data
(process-send-string *gnuplot-proc*
"5 -1\n4 -3.5\n3 9.5\n")
;; end of data, after this gnuplot would pop up interactive window
(process-send-string *gnuplot-proc* "e\n")
With such asynchronous process it's easy to write something to make it interactively update plot as new data comes along.
You might have a look at the orgplot mode, which ties gnuplot into emacs org tables.
http://orgmode.org/worg/org-tutorials/org-plot.html
You could use eazy-gnuplot, I do. See it here: eazy-gnuplot examples. The github repo is here: github repo. I don't have more time to provide an example here, sorry.
I am not experienced with Gnuplot, and a quick search didn't turn up too much information. But perhaps i can propose an approach. Say you chunk your input, for example '(1 2 3 4 5) would be '((1) (1 2) (1 2 3) (1 2 3 4) (1 2 3 4 5)), you can then generate a plot for each, and use a graphics library like lispbuilder-sdl to display it in a window with a time delay. SDL has a timer and it can display images just fine.