defstruct is not supported in ClojureScript - it would appear to be by design. Now it may be that this is effectively a deprecated part of the Clojure language, and the designers of ClojureScript were just hoping everyone had moved on. (But this is my speculation).
My question is: What was the reasoning behind ClojureScript not needing Clojure's defstruct?
defstruct is effectively deprecated in the language, in favor of defrecord. We are supposed to move on in (JVM-based) Clojure, so I would expect Clojurescript to be the same. See the following:
Clojure: data structures: "Note: Most uses of StructMaps would now be better served by records."
ClojureDocs: defstruct comment by steveminer: "Structs are obsolete. Use records instead. See defrecord."
The forthcoming The Joy of Clojure, 2nd ed. (prerelease V9 edition) by Fogus and Houser says "With the advent of defrecord, the need for structs has been nearly eliminated, and therefore structs aren’t covered in this book." (p. 322)
Also note that Programming Clojure, 2nd ed. by Halloway and Bedra covers defrecord but not defstruct (although there are some passing mentions of structures--maybe accidentally left from the 1st ed.).
I guess all the cool people are using defrecord these days. :-)
Alex Miller's answer to "Where should I use defrecord in clojure?" has a nice discussion of advantages (and disadvantages) of defrecord, although he's not, primarily, comparing it with defstruct.
Related
I'm reading some Clojure code at the moment that has a bunch of uninitialised values as nil for a numeric value in a record that gets passed around.
Now lots of the Clojure libraries treat this as idiomatic. Which means that it is an accepted convention.
But it also leads to NullPointerException, because not all the Clojure core functions can handle a nil as input. (Nor should they).
Other languages have the concept of Maybe or Option to proxy the value in the event that it is null, as a way of mitigating the NullPointerException risk. This is possible in Clojure - but not very common.
You can do some tricks with fnil but it doesn't solve every problem.
Another alternative is simply to set the uninitialised value to a symbol like :empty-value to force the user to handle this scenario explicitly in all the handling code. But this isn't really a big step-up from nil - because you don't really discover all the scenarios (in other people's code) until run-time.
My question is: Is there an idiomatic alternative to nil-punning in Clojure?
Not sure if you've read this lispcast post on nil-punning, but I do think it makes a pretty good case for why it's idiomatic and covers various important considerations that I didn't see mentioned in those other SO questions.
Basically, nil is a first-class thing in clojure. Despite its inherent conventional meaning, it is a proper value, and can be treated as such in many contexts, and in a context-dependent way. This makes it more flexible and powerful than null in the host language.
For example, something like this won't even compile in java:
if(null) {
....
}
Where as in clojure, (if nil ...) will work just fine. So there are many situations where you can use nil safely. I'm yet to see a java codebase that isn't littered with code like if(foo != null) { ... everywhere. Perhaps java 8's Optional will change this.
I think where you can run into issues quite easily is in java interop scenarios where you are dealing with actual nulls. A good clojure wrapper library can also help shield you from this in many cases, and its one good reason to prefer one over direct java interop where possible.
In light of this, you may want to re-consider fighting this current. But since you are asking about alternatives, here's one I think is great: prismatic's schema. Schema has a Maybe schema (and many other useful ones as well), and it works quite nicely in many scenarios. The library is quite popular and I have used it with success. FWIW, it is recommended in the recent clojure applied book.
Is there an idiomatic alternative to nil-punning in Clojure?
No. As leeor explains, nil-punning is idiomatic. But it's not as prevalent as in Common Lisp, where (I'm told) an empty list equates to nil.
Clojure used to work this way, but the CL functions that deal with lists correspond to Clojure functions that deal with sequences in general. And these sequences may be lazy, so there is a premium on unifying lazy sequences with others, so that any laziness can be preserved. I think this evolution happened about Clojure 1.2. Rich described it in detail here.
If you want option/maybe types, take a look at the core.typed library. In contrast to Prismatic Schema, this operates at compile time.
I've been reading Structure and Interpretation of Computer Programs. Lisp is teaching me to think in its way. As a java developer, I wish to learn clojure.
I know clojure is similar to lisp. So my question is, does learning Lisp help me learn clojure easily? Are there similar concepts in both languages?
Clojure share many similarities with other Lisps. SICP is a great book and although it focuses on Scheme a lot of what it teaches you will be directly relevant to Clojure.
If you lean one Lisp then it will be substantially easier to pick up another.
There are however a couple of things about Clojure that make it "different" that are worth noting:
It extends classic Lisp syntax with vectors [], hashmaps {} and sets #{} as well as the traditional lists ().
It is more of a functional programming language in style than most other Lisps - pretty much everything is immutable, sequences are lazy by default etc. In some ways Clojure feels quite strongly influenced by Haskell
Clojure embraces the Java platform in a big way - it runs on the JVM you can easily use Java libraries directly. As a result, although you don't strictly need to know Java to be effective in Clojure it helps to have an understanding of the Java ecosystem and tools.
The Clojure STM system / support for concurrency is very innovative and different. Worth watching this video: http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey
Take this with a grain of salt; I'm a Common Lisper with some Scheme experience who's just getting started on Clojure, so I'm by no means an expert yet. You may want to google others' experiences.
It looks like the differences between Clojure and CL/Scheme are mostly in the minute details. The overarching principles are more or less the same, and it doesn't seem like learning Clojure will significantly change how you think about programming, assuming you already know one of the other Lisps. There's a much greater emphasis on immutability and functional programming than you find even in Scheme, and a few functions are named differently, and you need to balance parens/brackets/curlies rather than just parens, but that's pretty much it at the language level.
Having learned CL/Scheme, it seems that I'm having a much easier time of Clojure so far than I otherwise might.
As a final thought, working through SICP and the accompanying lectures is worth your time even if you plan to never look at Scheme again. It teaches a lot of generally useful CompSci principles, and a particular way of thinking that'll help you as a developer with whatever language you end up using.
Each language has its own set of nuances. You are currently learning Lisp's little quirks (assuming Common Lisp/CL), but pick up another language, let alone a second Lisp dialect, and you'll learn those quirks/differences/nuances, too.
Unless you have loads of time to learn, I would learn Clojure if you are interested in programming in it, Lisp if you are interested in programming in that.
Learning Lisp isn't a bad thing, because you'll get used to learning how Lisp dialects differ from Algol-C based languages. For that matter, the same argument could be made about learning Scheme.
Until Clojure, I programmed in similar languages, but even Bliss-32 and PL/I IMHO are more similar to C and Java then they are the Lisp dialects. Learning Clojure required on my part -- and is still requiring -- an even greater mental realignment than going from C to C++ (in the 90s).
I enjoy the realignment, but it is gradual, with a learning curve.
I went down the same path, since a friend of mine was an old Lisper made me learn Lisp out of interest. He started hacking back in the early 70's, and worked for some of the Lisp companies. Whenever we were talking about programming languages, he'd refer to concepts found in Lisp, and I felt I never quite got what he ment.
Learning Lisp was a great start into Clojure for me, and I ended up with Clojure since I was looking for a Lisp capable of running on ARM CPUs. In my eyes, Lisp is less complex, since it's not integrated with the Java VM, and without knowing Java well it would much more difficult to understand Clojure than Lisp. I can only say, having a good basic understanding of Lisp definitely helped me when learning Clojure.
I want to learn new language and I thought to start with Lisp. I want to know if I learn Lisp do I also know Clojure ( with minimal effort ), is there big syntax differences between Lisp and Clojure ?
There are not big syntax differences (mostly because Lisp family languages have almost no syntax), but there are certainly differences in other areas. Clojure has a lot of modern programming features particularly suited to high scalability (actors, references, etc) that are not present as such in a "classic" Lisp (such as Common Lisp).
Clojure is an active, well supported dialect of Lisp. If you want to learn a Lisp, you can't really go wrong with Clojure.
You may find more information in the answers to Which Lisp should I learn? .
90% of what you learn while studying your first Lisp will carry over to your next.
I think it's fair to say that if you learn the principles of LISP you will also know the principles of Clojure and vice-versa. They are all rooted in the same philosophy, emphasising things such as:
Code is data. Macros are just normal functions that manipulate code.
Use of S-expressions to represent data and code.
The concept of a list / sequence as a fundamental structure.
Functional programming with first-class functions.
Apart from that, there are lots of differences in syntax, libraries, runtime environments etc. The difference in my view is probably about the same as C# vs. C++ - if you know one well, then the core concepts will be familiar but there are still a lot of fundamental differences.
See this list of ways that Clojure is different from other Lisps
I'm assuming by Lisp you mean Common Lisp, since 'Lisp' itself is more of a family of languages (that includes Clojure) than a single specific language.
There are some syntactical changes in that Clojure was intended to be a more modern Lisp. For instance you can create vectors with []s, maps with {}s, which are not part of Common Lisp. And of course the Java interop inevitably becomes a significant part of Clojure.
Clojure uses vectors as lambda parameters (arguments values), but you can use a macro to write versions of defun and lambda in Common lisp that will look similar . Clojure also has access to Java Object methods and fields using a period (i.e. ".") and the name of the method or field which looks like a normal function call.
(.toString 10) - will call the method toString on number 10 but .toString is not a function. if you try to check the value of .toString it throws an exception that .toString is not a defined symbol.
And also with quasi-quotation (mostly in macros) instead of using a coma for unquote as in Common lisp, Clojure use a tilde.
McCarthy's original Lisp and some number of incarnations thereafter did not have a macro facility like we now have in Common Lisp, Clojure, Scheme, etc... This I know.
However, it is unclear to me exactly how macros came to be, what implementation(s) had them first, and what motivated them. References to papers and source would be ideal if you please.
From The Evolution of Lisp (PDF):
Macros appear to have been introduced into Lisp by Timothy P. Hart in 1963 in a short MIT AI Memo [Hart, 1963]
See:
AIM-57 Author[s]: Timothy P. Hart
MACRO Definitions for LISP
October 1963
ftp://publications.ai.mit.edu/ai-publications/0-499/AIM-057.ps
ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-057.pdf
In LISP 1.5 special forms are used for
three logically separate purposes: a)
to reach the alist, b) to allow
functions to have an indefinite number
of arguments, and c) to keep arguments
from being evaluated. New LISP
interpreters can easily satisfy need
(a) by making the alist a SPECIAL-type
or APVAL-type entity. Uses (b) and (c)
can be replaced by incorporating a
MACRO instruction expander in define.
I am proposing such an expander.
John Shutt's PhD thesis first part concerns the history of lisps, including the introduction of macros, I believe. It's not entirely clear to me on reading, but it seems that he claims that macros are more-or-less identified with an "extensible languages" movement (which is independent of lisp), and that M.D. McIlroy's 1960 paper, "Macro Extension Instructions of Compiler Languages", was foundational to the extensible languages movement... implying that macros were introduced to the academic literature in 1960.
I find myself attached to a project to integerate an interpreter into an existing application. The language to be interpreted is a derivative of Lisp, with application-specific builtins. Individual 'programs' will be run batch-style in the application.
I'm surprised that over the years I've written a couple of compilers, and several data-language translators/parsers, but I've never actually written an interpreter before. The prototype is pretty far along, implemented as a syntax tree walker, in C++. I can probably influence the architecture beyond the prototype, but not the implementation language (C++). So, constraints:
implementation will be in C++
parsing will probably be handled with a yacc/bison grammar (it is now)
suggestions of full VM/Interpreter ecologies like NekoVM and LLVM are probably not practical for this project. Self-contained is better, even if this sounds like NIH.
What I'm really looking for is reading material on the fundamentals of implementing interpreters. I did some browsing of SO, and another site known as Lambda the Ultimate, though they are more oriented toward programming language theory.
Some of the tidbits I've gathered so far:
Lisp in Small Pieces, by Christian Queinnec. The person recommending it said it "goes from the trivial interpreter to more advanced techniques and finishes presenting bytecode and 'Scheme to C' compilers."
NekoVM. As I've mentioned above, I doubt that we'd be allowed to incorporate an entire VM framework to support this project.
Structure and Interpretation of Computer Programs. Originally I suggested that this might be overkill, but having worked through a healthy chunk, I agree with #JBF. Very informative, and mind-expanding.
On Lisp by Paul Graham. I've read this, and while it is an informative introduction to Lisp principles, is not enough to jump-start constructing an interpreter.
Parrot Implementation. This seems like a fun read. Not sure it will provide me with the fundamentals.
Scheme from Scratch. Peter Michaux is attacking various implementations of Scheme, from a quick-and-dirty Scheme interpreter written in C (for use as a bootstrap in later projects) to compiled Scheme code. Very interesting so far.
Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages, recommended in the comment thread for Books On Creating Interpreted Languages. The book contains two chapters devoted to the practice of building interpreters, so I'm adding it to my reading queue.
New (and yet Old, i.e. 1979): Writing Interactive Compilers and Interpreters by P. J. Brown. This is long out of print, but is interesting in providing an outline of the various tasks associated with the implementation of a Basic interpreter. I've seen mixed reviews for this one but as it is cheap (I have it on order used for around $3.50) I'll give it a spin.
So how about it? Is there a good book that takes the neophyte by the hand and shows how to build an interpreter in C/C++ for a Lisp-like language? Do you have a preference for syntax-tree walkers or bytecode interpreters?
To answer #JBF:
the current prototype is an interpreter, and it makes sense to me as we're accepting a path to an arbitrary code file and executing it in our application environment. The builtins are used to affect our in-memory data representation.
it should not be hideously slow. The current tree walker seems acceptable.
The language is based on Lisp, but is not Lisp, so no standards compliance required.
As mentioned above, it's unlikely that we'll be allowed to add a full external VM/interpreter project to solve this problem.
To the other posters, I'll be checking out your citations as well. Thanks, all!
Short answer:
The fundamental reading list for a lisp interpreter is SICP. I would not at all call it overkill, if you feel you are overqualified for the first parts of the book jump to chapter 4 and start interpreting away (although I feel this would be a loss since chapters 1-3 really are that good!).
Add LISP in Small Pieces (LISP from now on), chapters 1-3. Especially chapter 3 if you need to implement any non-trivial control forms.
See this post by Jens Axel Søgaard on a minimal self-hosting Scheme: http://www.scheme.dk/blog/2006/12/self-evaluating-evaluator.html .
A slightly longer answer:
It is hard to give advice without knowing what you require from your interpreter.
does it really really need to be an interpreter, or do you actually need to be able to execute lisp code?
does it need to be fast?
does it need standards compliance? Common Lisp? R5RS? R6RS? Any SFRIs you need?
If you need anything more fancy than a simple syntax tree walker I would strongly recommend embedding a fast scheme subsystem. Gambit scheme comes to mind: http://dynamo.iro.umontreal.ca/~gambit/wiki/index.php/Main_Page .
If that is not an option chapter 5 in SICP and chapters 5-- in LISP target compilation for faster execution.
For faster interpretation I would take a look at the most recent JavaScript interpreters/compilers. There seem to be a lot of thought going into fast JavaScript execution, and you can probably learn from them. V8 cites two important papers: http://code.google.com/apis/v8/design.html and squirrelfish cites a couple: http://webkit.org/blog/189/announcing-squirrelfish/ .
There is also the canonical scheme papers: http://library.readscheme.org/page1.html for the RABBIT compiler.
If I engage in a bit of premature speculation, memory management might be the tough nut to crack. Nils M Holm has published a book "Scheme 9 from empty space" http://www.t3x.org/s9fes/ which includes a simple stop-the-world mark and sweep garbage collector. Source included.
John Rose (of newer JVM fame) has written a paper on integrating Scheme to C: http://library.readscheme.org/servlets/cite.ss?pattern=AcmDL-Ros-92 .
Yes on SICP.
I've done this task several times and here's what I'd do if I were you:
Design your memory model first. You'll want a GC system of some kind. It's WAAAAY easier to do this first than to bolt it on later.
Design your data structures. In my implementations, I've had a basic cons box with a number of base types: atom, string, number, list, bool, primitive-function.
Design your VM and be sure to keep the API clean. My last implementation had this as a top-level API (forgive the formatting - SO is pooching my preview)
ConsBoxFactory &GetConsBoxFactory() { return mConsFactory; }
AtomFactory &GetAtomFactory() { return mAtomFactory; }
Environment &GetEnvironment() { return mEnvironment; }
t_ConsBox *Read(iostream &stm);
t_ConsBox *Eval(t_ConsBox *box);
void Print(basic_ostream<char> &stm, t_ConsBox *box);
void RunProgram(char *program);
void RunProgram(iostream &stm);
RunProgram isn't needed - it's implemented in terms of Read, Eval, and Print. REPL is a common pattern for interpreters, especially LISP.
A ConsBoxFactory is available to make new cons boxes and to operate on them. An AtomFactory is used so that equivalent symbolic atoms map to exactly one object. An Environment is used to maintain the binding of symbols to cons boxes.
Most of your work should go into these three steps. Then you will find that your client code and support code starts to look very much like LISP too:
t_ConsBox *ConsBoxFactory::Cadr(t_ConsBox *list)
{
return Car(Cdr(list));
}
You can write the parser in yacc/lex, but why bother? Lisp is an incredibly simple grammar and scanner/recursive-descent parser pair for it is about two hours of work. The worst part is writing predicates to identify the tokens (ie, IsString, IsNumber, IsQuotedExpr, etc) and then writing routines to convert the tokens into cons boxes.
Make it easy to write glue into and out of C code and make it easy to debug issues when things go wrong.
The Kamin Interpreters from Samuel Kamin's book Programming Languages, An Interpreter-Based Approach, translated to C++ by Timothy Budd. I'm not sure how useful the bare source code will be, as it was meant to go with the book, but it's a fine book that covers the basics of implementing Lisp in a lower-level language, including garbage collection, etc. (That's not the focus of the book, which is programming languages in general, but it is covered.)
Lisp in Small Pieces goes into more depth, but that's both good and bad for your case. There's a lot of material on compiling and such that won't be relevant to you, and its simpler interpreters are in Scheme, not C++.
SICP is good, definitely. Not overkill, but of course writing interpreters is only a small fraction of the book.
The JScheme suggestion is a good one, too (and it incorporates some code by me), but won't help you with things like GC.
I might flesh this out with more suggestions later.
Edit: A few people have said they learned from my awklisp. This is admittedly kind of a weird suggestion, but it's very small, readable, actually usable, and unlike other tiny-yet-readable toy Lisps it implements its own garbage collector and data representation instead of relying on an underlying high-level implementation language to provide them.
Check out JScheme from Peter Norvig. I found this amazingly simple to understand and port to C++. Uh, dunno about using scheme as a scripting language though - teaching it to jnrs is cumbersome and feels dated (helloooo 1980's).
I would like to extend my recommendation for Programming Languages: Application and Interpretation. If you want to write an interpreter, that book takes you there in a very short path. If you read through writing the code you read and doing the exercise you end up with a bunch of similar interpreters but different (one is eager, the other is lazy, one is dynamic, the other has some typing, one has dynamic scope, the other has lexical scope, etc).