Learning Scheme Macros. Help me write a define-syntax-rule - functional-programming

I am new to Scheme Macros. If I just have one pattern and I want to combine the define-syntax and syntax-rules, how do I do that?
(define-syntax for
(syntax-rules (from to)
[(for i from x to y step body) ...]
[(for i from x to y body) ...]))
If I just have one for, how do I combine the syntax definition and the rule?
Thanks.

In other words, you decided that for really only needs one pattern and want to write something like:
(defmacro (for ,i from ,x to ,y step ,body)
; code goes here
)
There is nothing built-in to Scheme that makes single-pattern macros faster to write. The traditional solution is (surprise!) to write another macro.
I have used defsubst from Swindle, and PLT Scheme now ships with define-syntax-rule which does the same thing. If you are learning macros, then writing your own define-syntax-rule equivalent would be a good exercise, particularly if you want some way to indicate keywords like "for" and "from". Neither defsubst nor define-syntax-rule handle those.

Related

Knowing when what you're looking at must be a macro

I know there is macro-function, explained here, which allows you to check, but is it also possible in simply reading lisp source to sometimes infer of what you're looking at "that must be a macro"? (assuming of course you have never seen the function/macro before).
I'm fairly sure the answer is yes, but as this seems so fundamental, I thought worth asking, especially because any nuances on this may be valuable & interesting to know about.
In Paul Graham's ANSI Common Lisp, p70, he is describing how to use defstruct.
When I see (defstruct point x y), were I to know absolutely nothing about what defstruct was, this could just as well be a function.
But when I see
(defstruct polemic
(subject "foo")
(effect "bar"))
I know that must be a macro because (let's assume), I also know that subject and effect are undefined functions. (I know that because they error with undefined function when called 'at the top level'(?)) (if that's the right term).
If the two list arguments to defstruct above were quoted, it would not be so simple. Because they're not quoted, it must be a macro.
Is it as simple as that?
I've changed the field names slightly from those used on the book to make this question clearer.
Finally, Graham writes:
"We can specify default values for structure fields by enclosing the field name and a default expression in a list in the original definition"
What I'm noticing is that that's true but it is not a (quoted) list. Would any readers of this post have phrased the above sentence at all differently (given that macros haven't been introduced in the book yet (though I have a basic awareness of what they are)).
My feeling is it's not a "data list" those default expressions are enclosed in. (apologies for bad terminology) - seeking how rightly to conceptualise here.
In general, you're right: if there's some nesting inside the call and you are sure that the car's of the nested lists aren't functions - it's a macro.
Also, almost always, def-something and with-something are macros.
But there's no guarantee. The question is, what are you trying to accomplish? Some code walking/transformation or external processing (like in an editor). For the latter, you should keep in mind that full control is possible only if you perform code evaluation, although heuristics (like in Emacs) can take you pretty far. Or you just want to develop your intuition for faster code reading...
There is a set of conventions that identify quite cleary what forms are supposed to be macros, simply by mimicking the syntax of existing macros or special operators of CL.
For example, the following is a mix of various imaginary macros, but even without knowing their definition, the code shouldn't be too hard to figure out:
(defun/typed example ((id (integer 0 10)))
(with-connection (connection (connect id))
(do-events (event connection)
(event-case event
(:quit (&optional code) (return code))))))
The usual advice about macros is to avoid them if possible, so if you spot something that doesn't make sense as a lisp expression, it probably is, or is enclosed in, a macro.
(defstruct point x y)
[...] were I to know absolutely nothing about what defstruct was, this could just as well be a function.
There are various hints that this is not a function. First of all, the name starts with def. Then, if defstruct was a function, then point, x and y would all be evaluated before calling the function, and that means the code would be relying on global variables, even though they are not wearing earmuffs (e.g. *point*, *x*, *y*), and you probably won't find any definition for them in the preceding forms (or later in the same compilation unit). Also, if it was a function, the result would be discarded directly since it is not used (this is a toplevel form). That only indicates the probable presence of side-effects, but still, this would be unusual.
A top-level function with side-effects would look like this instead, with quoted data:
(register-struct 'point '(x y))
Finally, there are cases where you cannot easily guess if you are using a macro or a function:
(my-get object :slot)
This could be a function call, or you could have a macro that turns the above to (aref object 0) (assuming :slot is the zeroth slot in object, because all your objects are assumed to be of a certain custom type backed by a vector). You could also have compiler macros. In case of doubt, try to macroexpand it and look at the documentation.

How do I get turnstile to work in isabelle?

I was wondering how do I get turnstile to work in Isabelle 2017. I new to the program and have been able to work some thereoms but I can't figure out how to get the turnstile symbol to work. Do I have change imports or is there something else I have to do?
Thanks.
Okay, so it seems like you want to define some custom syntax involving the turnstile symbol.
This is described in Sections 8.2 and 8.3 of the Isabelle/Isar reference manual (and some more advanced stuff in Sections 8.5.2 and 8.5.3). You can do a lot of fancy custom syntax with Isabelle: the list syntax [1, 2, 3] for Cons 1 (Cons 2 (Cons 3 Nil)), for example, is defined entirely in ‘user space’, as is the list comprehension syntax [x + y. x ← xs, y ← ys, x ≠ y]. These are pretty complicated.
However, in most cases, you only need a very small fragment of all that power: As outline in Section 8.2 of isar-ref, you can annotate syntax directly to constants as you define them (e.g. with definition, primrec, fun, datatype) by either using something like infixl, infixr, or binder, or by directly providing a mixfix syntax specification. The tricky part here is often defining the precedences so that they don't clash with other stuff.
If you get this wrong, you will get warnings (not upon defining the syntax, but upon using it) telling you that there are ambiguous parse trees and that you should perhaps try to disambiguate your syntax by providing better mixfix priorities.
For examples of how this looks in practice you can look, well, basically at any Isabelle syntax you already know by going to where it is defined and looking at the mixfix specification.
One place that comes to my mind is the ~~/src/HOL/IMP directory, in particular the files Hoare.thy and Types.thy. They define some custom syntax, some of which even includes the turnstile symbol.

Recursively run through a vector in Clojure

I'm just starting to play with Clojure.
How do I run through a vector of items?
My naive recursive function would have a form like the classic map eg.
(defn map [f xs] (
(if (= xs [])
[]
(cons (f (first xs)) (map f (rest xs))
)
))
The thing is I can't find any examples of this kind of code on the web. I find a lot of examples using built-in sequence traversing functions like for, map and loop. But no-one doing the raw recursive version.
Is that because you SHOULDN'T do this kind of thing in Clojure? (eg. because it uses lower-level Java primitives that don't have tail-call optimisation or something?)?
When you say "run through a vector" this is quite vague; as Clojure is a lisp and thus specializes in sequence analysis and manipulation, the beauty of using this language is that you don't think in terms "run through a vector and then do something with each element," instead you'd more idiomatically say "pull this out of a vector" or "transform this vector into X" or "I want this vector to give me X".
It is because of this type of perspective in lisp languages that you will see so many examples and production code that doesn't just loop/recur through a vector but rather specifically goes after what is wanted in a short, idiomatic way. Using simple functions like reduce map filter for into and others allow you to elegantly move over a sequence such as a vector while simultaneously doing what you want with the contents. In most other languages, this would be at least 2 different parts: the loop, and then the actual logic to do what you want.
You'll often find that if you think about sequences using the more imperative idea you get with languages like C, C++, Java, etc, that your code is about 4x longer (at least) than it would otherwise be if you first thought about your plan in a more functional approach.
Clojure re-uses stack frames only with tail-recurstion and only when you use the explicit recur call. Everything else will be stack consuming. The above map example is not tail recursive because the cons happens after the recursive call so it can't be TCO'd in any language. If you switch it to use the continuation passing style and use an explicit call to recur instead of map then you should be good to go.

Fixed-Point Combinators

I am new to the world of fixed-point combinators and I guess they are used to recurse on anonymous lambdas, but I haven't really got to use them, or even been able to wrap my head around them completely.
I have seen the example in Javascript for a Y-combinator but haven't been able to successfully run it.
The question here is, can some one give an intuitive answer to:
What are Fixed-point combinators, (not just theoretically, but in context of some example, to reveal what exactly is the fixed-point in that context)?
What are the other kinds of fixed-point combinators, apart from the Y-combinator?
Bonus Points: If the example is not just in one language, preferably in Clojure as well.
UPDATE:
I have been able to find a simple example in Clojure, but still find it difficult to understand the Y-Combinator itself:
(defn Y [r]
((fn [f] (f f))
(fn [f]
(r (fn [x] ((f f) x))))))
Though the example is concise, I find it difficult to understand what is happening within the function. Any help provided would be useful.
Suppose you wanted to write the factorial function. Normally, you would write it as something like
function fact(n) = if n=0 then 1 else n * fact(n-1)
But that uses explicit recursion. If you wanted to use the Y-combinator instead, you could first abstract fact as something like
function factMaker(myFact) = lamba n. if n=0 then 1 else n * myFact(n-1)
This takes an argument (myFact) which it calls were the "true" fact would have called itself. I call this style of function "Y-ready", meaning it's ready to be fed to the Y-combinator.
The Y-combinator uses factMaker to build something equivalent to the "true" fact.
newFact = Y(factMaker)
Why bother? Two reasons. The first is theoretical: we don't really need recursion if we can "simulate" it using the Y-combinator.
The second is more pragmatic. Sometimes we want to wrap each function call with some extra code to do logging or profiling or memoization or a host of other things. If we try to do this to the "true" fact, the extra code will only be called for the original call to fact, not all the recursive calls. But if we want to do this for every call, including all the recursive call, we can do something like
loggingFact = LoggingY(factMaker)
where LoggingY is a modified version of the Y combinator that introduces logging. Notice that we did not need to change factMaker at all!
All this is more motivation why the Y-combinator matters than a detailed explanation from how that particular implementation of Y works (because there are many different ways to implement Y).
To answer your second question about fix-point combinators other than Y. There are countably infinitely many standard fix-point combinators, that is, combinators fix that satisfy the equation
fix f = f (fix f)
There are also contably many non-standard fix-point combinators, which satisfy the equation
fix f = f (f (fix f))
etc. Standard fix-point combinators are recursively enumerable, but non-standard are not. Please see the following web page for examples, references and discussion.
http://okmij.org/ftp/Computation/fixed-point-combinators.html#many-fixes

What is define-struct in Racket and why are there no variables?

In one of my CS courses at university we have to work with Racket. Most of my programming time before university I spent with PHP and Java and also JavaScript. I know Racket is a functional programming language, just like JavaScript (Edit: Of course it isn't. But I felt like I was doing 'functional' programming with it, which after seeing the answers, is a wrong perception.) But I still don't understand some fundamental characteristics of Racket (Scheme).
Why are there no 'real' variables? Why is everything a function in Racket/Scheme? Why did the language designers not include them?
What is define-struct? Is it a function? Is it a class? I somehow, because of my PHP background, always think it's a class, but that can't be really correct.
My question here is I want to understand the concept of the language. I personally still think it's really strange and not like anything I worked with before, so my brain tries to compare it with JavaScript, but it just seems so different to me. Parallels/differences to JavaScript would help a lot!
There are 'real' variables in Racket. For example, if you write this
code
(define x 3)
the 'global' variable x will be set to value 3. If you now write
(set! x 4)
the variable x will change its value to 4. So, in Racket you can
have a 'normal' variables like in any 'normal' language, if you
want. The fact is that in Racket the preferred programming style is
functional as opposed to procedural. In functional programming style
variable mutation is discouraged.
define-struct is a Racket macro that you use to define 'structure
template' along with several other things. For example, if you
write:
(define-struct coord (x y))
you just defined a 'structure template' (i.e user type named coord
that have two "slots": x and y). After that, you can now:
create new "instance" of structure coord, for example like this:
(make-coord 2 3)
extract slot value from the structure object:
(coord-x (make-coord 2 3)) ;will return 2
or
(coord-y (make-coord 2 3)) ;will return 3
you can ask if some given object is just that structure. For
example, (coord? 3) will return #f, since 3 is not of type coord
structure, but
(coord? (make-coord 2 3)) ;will return #t
Perhaps the most popular or in-fashion way to program (using languages like C++, Javascript, and Java) has a few characteristics. You may take them for granted as self-evident, the only possible way. They include:
Imperative
You focus on saying "do this step, then this next step" and so on.
Using mutation.
You declare a variable, and keep assigning it different values ("mutate it").
Object-oriented.
You bundle code and data into classes, and declare instances of them as objects. Then you mutate the objects.
Learning Scheme or Racket will help you understand that these aren't the only way to go about it.
It might make your brain hurt at first, in the same way that a philosophy class might cause you to question things you took for granted. However unlike the philosophy class, there will be some practical pay-off to making brain hurt. :)
An alternative:
Functional (instead of imperative). Focus on expressions that return values, instead of making to-do lists of steps.
Immutable. Ditto.
Not object oriented. Using objects of classes can be a good approach to some problems, but not all. If you want to bundle code with data, there are some more general ways to go about it, such as closures with "let over lambda" and so on. Sometimes you don't need all the "baggage" of classes and especially inheritance.
Scheme and Racket make it easy to explore these ideas. But they are not "pure functional" like say Haskell, so if you really want to do imperative, mutable, object-oriented things you can do that, too. However there's not much point in learning Racket to do things the same way you would in Javascript.
Scheme very much has "real" variables.
The difference between a functional language (like Racket) and an imperative language (like JavaScript or PHP) is that in a functional language, you usually don't use mutable state. Variables are better thought of as names for values than as containers that can hold values. Instead of using things like looping constructs to change values in variables, you instead use recursion for flow control.
define-struct is a special syntactic form, kind of like keywords in other languages. (Unlike other languages, in Scheme you can create your own syntactic forms.) It defines a struct type, which is like a class but doesn't have methods. It also defines a number of functions that help you utilize your new struct type.
There are variables in Scheme.
> (define a 1)
#<unspecified>
> a
1
> (set! a 2)
#<unspecified>
> a
2
There are even mutable data structures in this language.
> (begin
> (define v (make-vector 4))
> (vector-set! v 0 'foo)
> (vector-set! v 1 'bar)
> (vector-set! v 2 'baz)
> (vector-set! v 3 'quux))
#<unspecified>
> v
#(foo bar baz quux)
Scheme is not a pure FP language; it does allow imperative programming, although it is mostly geared towards functional programming. That's a design choice that Scheme's inventors made.
define-struct is a special form; it's syntax, like the function or return keywords in JavaScript.

Resources