110 points · by nathell · 12y ago · 109 comments
(add 4 (mul 2 5)) vs.
add(4, mul(2, 5))
But that doesn't mean you should write bash like that. In fact, it is (IMO) very bad style to nest $(). When people complain about Lisp syntax, it's only partially about the RPN or the parens, its about the incredible amount of nesting.Funnily enough, of all things bash offers an alternative paradigm. Instead of nesting, you use filters:
# pseudocode
echo 2 | mul 5 | add 4
For example, you can write: nerrors=$(mycommand | grep error | sort | uniq | wc -l)
instead of: # pseudocode
nerrors=wc("-l", uniq(sort(grep("error", mycommand))))
I find this paradigm of "do A, then do B, then do C" much easier to think about than the nested "do C on the result of doing B on A". I wish more programming languages would embrace that kind of coding, which is basically functional, but in imperative or data-flow order. You have aspects of that in C# (LINQ), SQL, and some others. I know you can achive something like that in Haskell though Monads and `do`, though it feels a bit bolted on as a concession to having to do imperative stuff in a purely functional language. (And as nice Haskell is, it will probably never have the use base that bash has...)The closer equivalent to UNIX pipelining in Haskell is actually the simple "." operator, function composition. That pipeline would generally look more like
countLines = wc LineCount
countLines . uniq . sort . grep "error" $ mycommand
It's not a direct translation, because that is exactly neither legal Haskell (I'm munging program vs. some sort of shell here), nor exactly how you'd really do that in Haskell, however, pipelines of several functions composed together is idiomatic and frequently-used."though it feels a bit bolted on as a concession to having to do imperative stuff in a purely functional language"
It really isn't. IO is only one particular monadic thing; check out Parsec for some more fun. It only looks bolted on if you look very superficially, and you darned near have to bring the preconception in the first place to even briefly come to that conclusion. That idea basically comes from the misconception that "Haskell can't do side effects", then "Oh, well, this way of doing side effects must be a bad idea or something"... the first statement is false. Honestly, I miss the way Haskell does IO in other languages far more than I miss the way other languages do IO in Haskell. (To be clear, I do have both feelings, but the former is way more common.)
(!) = flip ($)
Which then allows me to do things like mycommand ! grep "error" ! sort ! uniq ! wc lineCount
Which is nice because it visually resembles `|` (which is a reserved symbol in Haskell).Similarly for fmap:
(<!>) = flip (<$>)
result <- get <!> table <!> lookup "foo"
print result ! liftIO
Or for function composition: (~>) = flip (.)
doStuff = reverse ~> head ~> negate ~> print
doStuff [1,2,3]
That being said, lisp does seem far more suited to shell programming than Haskell, because every function is variadic. What would probably be nice (and probably has been done) is a Lisp with syntax extended to include a few symbols to allow bash commands like |, >, etc: $ def nth-line (n) (read a | head -(n) | tail -n 1)
$ ssh -i .ssh/some.pem (python show_servers.py | grep 'cool server' | cut -d ' '
-f 3 | nth-line 1)...or read any of the older Haskell books and tutorials, which all seemed to start in pure expression-land and attempt to stay there as long as possible (which is good programming style, don't get me wrong; but learning is different). IO and other monadic things are treated like huge and scary monsters that must be left until the very last possible moment, if treated at all, because they're HUGE AND SCARY!!!!1! Aaaaahhhhhh!
Well said - this is very much my experience as well.
(->> (command) (grep "error") sort uniq (wc :-l)
Does anyone think (wc :-l (uniq (sort (grep "error" (command)))))
is a better option? And instead of typing that out manually, I just used the REPL. user=> (use 'clojure.walk)
nil
user=> (macroexpand-all '(->> (command) (grep "error") sort uniq (wc :-l)))
(wc :-l (uniq (sort (grep "error" (command)))))
Even without macros you can still setup nice-looking chaining with generators and coroutines. "Too much nesting" seems like the wrong complaint. "C:/tmp/adinst.log" utf16 file-lines [ "SEARCH" swap start ] filter members length
File is opened into a sequence of lines, then the sequence is filtered so that only lines containing "SEARCH" remain, then members removes duplicates, then length gets the number of elements left in the sequence. In the shell, "|" is the function composition operator, in haskell it's "." In Factor, any whitespace is function composition! x -: f = f x
and boom, a Unix style pipe.(Courtesy of Learn You a Haskell, http://learnyouahaskell.com/a-fistful-of-monads, but using no actual monads).
I've played around with Elixir a bit and while I don't quite have a nail to hit with that particular hammer, it has been really fun and mind-expanding (my first functional language!).
The first was the mental conversion to/from f(a,b,c) to (f a b c) which is just moving the opening parenthesis one token to the left and seeing both commas and whitespace as "something between the tokens that really matter".
The remaining half was starting with Clojure. It is a Lisp whose constructs are really optimized towards dumping extraneous parentheses so it is easier not to get lost in the nesting levels.
Although Clojure still has a `cons` it has been replaced by `seq` as the fundamental abstraction. Clojure takes advantage of being fully managed code and in a sense is as much a Lisp as C# is a C [if we were inclined to think of C as a genre, else Algol?].
It seems this, combined with a formally incorporating a DSL of the kind a experienced Lisper (such as Hickey) might create for writing programs gives Clojure it's syntax: e.g. [x y] is syntactically like a quoted list and writing a macro is the sort of thing hubris drives lazy impatient Lispers to do. In special forms [x y] is like a different more complex macro, but again the sort of thing people would write for themselves. In other Lisps the ad hoc nature of such macros however makes other people's code notoriously hard to follow.
Yeah, cons is like malloc, except that the object it creates is automatically memory managed / garbage collected. There is no corresponding "free" call. Actually, that means cons is not like malloc.
Clojure takes advantage of being fully managed code
Do you realize that Lisp uses automatic memory management (just like the JVM or CLR)?
Why are there no Fortran machines or Algol Machines or C machines?
The `cons` cell is a raw memory structure, just one step removed from assembly and originally accessed directly in machine code with `car` and `cdr`. It's associated symbol is literally a pointer directly to a memory location. It's so close to assembly language that thirty years ago implementing it directly in hardware was considered practical.
> Although Clojure still has a `cons` it has been replaced by `seq` as the fundamental abstraction.
Common Lisp has lists and sequences as abstractions. But it does not take away the low-level operations.
I'm not making a case that Clojure is better than other Lisps - getting rid of `cons` and relying on the JVM has makes typing more critical in an environment that retains a degree of type opacity typical of dynamic type systems.
>Clojure takes advantage of being fully managed code
>writing a macro is the sort of thing hubris drives lazy impatient Lispers to do
The ignorance of Clojure programmers is really incredible.
(foo '(1 2 3)) simply becomes (foo [1 2 3])
Common Lisp:
A vector:
CL-USER 34 > #(1 2 3)
#(1 2 3)
A string: CL-USER 35 > "1 2 3"
"1 2 3"
A structure: CL-USER 36 > #S(FOO :A 1 :B 2 :C 3)
#S(FOO :A 1 :B 2 :C 3) lambda (x)(+ x 1)
defun f (x)(+ x 1)
Syntactically `(x)` looks like it should be evaluated, but isn't because there are special rules for special forms, and each special form can have it's own rules: let ((x 7)(y 3))
(+ x y)
is a whole `nother set of syntactical rules which are even more in conflict with normal rules of evaluation.Scheme, keeps the let and uses a syntax for `define` that mimics the function call rather than the lambda.
define (f x) (+ x 1)
f 1
In Clojure the use of a vector for `defn` arguments follows it's formal lambda form like Common Lisp and is very much consistent with Clojure's rules for evaluation. fn [x] (+ x 1)
defn f [x] (+ x 1)
Likewise Clojure's `let` syntax does not require wetware parsing to recognize what gets evaluated and what doesn't. let [x 1
y 3]
(+ x y)
What I am appreciating about Clojure as a language is that it prunes some historic artifacts from the Lisp family tree. Raw memory allocation with `cons` made sense when human memory could retain more facts than a computer's fast memory. This meant it was easy to think of useful programs too big to fit in memory. That's distinctly harder today where doubling fast memory is less than $300 for the vast majority of computers.Lisp was developed as a direct improvement over assembly. Clojure was developed as a direct improvement over Java over C++ over C over assembly. It's a rethinking of what a Lisp needs (when backwards compatibility is ignored). It's an interesting design.
'(1 2 3)
constructs a value of type list, while this:
[1 2 3]
constructs a value of type vector.
They are not the same and you cannot say that one somehow becomes the other. And from what I remember Clojure does have a list data-type and it still needs to be quoted, except for empty list literal, (), which is self-evaluating.
So, in Clojure you need to quote your lists, exactly like in many other Lisps, and you have literals for other data structures, exactly like in many other Lisps ([] in Elisp, #() in Racket, CL covered by lispm). But of course Clojure is so much more readable because it has so few parentheses in comparison... to Java, I suppose.
Also
(let [my-list '(1 2 3)
my-vec [1 2 3]
(= my-list my-vec))
returns `true`. It's one of the subtleties of Clojure and its implementation on top of Java's object and type systems, and one which can be difficult to parse out at the lower end of the learning curve...which is where I am.Lisp adds just one rule: a Lisp program is an sexp whose root node is a function symbol.
Naturally, since sexps nest, Lisp programs can nest.
The author demonstrates nested computation with bash's $( .. ) syntax. Lisp, by the nature of the sexps, is nested computations. I think the author almost hits the nail on the head here:
> Our two basic rules — program-name-first and $()-for-composition — allowed us to explicitly specify the order of evaluation, so there was no need to do any fancy parsing beyond what the shell already provides.
Sexps provide nesting/composition. Lisp just means program-name-first.
Now you explain these three examples. All have a symbol at the start of the list.
* (let foo bar)
; in: LET FOO
; (LET FOO
; BAR)
;
; caught ERROR:
; Malformed LET bindings: FOO.
;
; compilation unit finished
; caught 1 ERROR condition
* (lambda a b)
; in: LAMBDA A
; (LAMBDA A B)
;
; caught ERROR:
; The lambda expression has a missing or non-list lambda list:
; (LAMBDA A B)
* (defun foo (a) (+ a 10) (declare (fixnum a))
)
; in: DEFUN FOO
; (DECLARE (FIXNUM A))
;
; caught WARNING:
; There is no function named DECLARE. References to DECLARE in some contexts
; (like starts of blocks) have special meaning, but here it would have to be a
; function, and that shouldn't be right.
Obviously the SYNTAX for LET, LAMBDA, DEFUN, ... is more complex than what you think.Looks like there is Lisp code where it is not sufficient to have a symbol at the start of an s-expression. There seem to be more constraints to the allowed s-expressions.
For example the syntax for LET is:
let ({var | (var [init-form])}*) declaration* form*Your special forms will either be natively supported or they'll be written with a defmacro in terms of native special forms. The definitions can't be circular, of course: if defmacro was used to define if, then if cannot be used in the definition of defmacro.
So my "rule" isn't really a hard rule. Macros/forms are the exception. But it seems more intuitive for me to think in terms of functions whenever possible, then to bend the rule when macros get involved.
Macros are not for implementing special forms.
> Macros/forms are the exception.
Common Lisp has around 30 special forms and many more macros. Some with a special complex syntax, like LOOP.
Programming Lisp with only function call syntax is practically impossible. LAMBDA, DEFUN, ... are already having additional syntax.
Yes, it really does. Let me finish that chain of reasoning for you:
S-expressions have syntax. Lisp is a subset of the sexps. Therefore, Lisp has syntax. QED
Yes, Lisp has very simple syntax. Yes, it's neat that eval can be implemented in a few dozen lines of Lisp. But as a practical matter Lisp is a programming language like any other. This sort of mysticism does not encourage people to learn Lisp or help the ideas behind Lisp become more mainstream.
* s-expressions are a syntax for data
* Lisp syntax is expressed on top of s-expressions, reusing s-expression syntax for data
* Lisp has built-in syntax for several constructs: lambda, let, block, setq, if, ...
Many programming languages have some form of prefix operators.
Btw., some Lisps allow to omit outer parentheses in a Listener (aka REPL):
CL-USER 30 > delete-file "/Lisp/foo"
NILhttp://draketo.de/light/english/wisp-lisp-indentation-prepro...
For example RLISP:
SYMBOLIC PROCEDURE SMEMBER(U,V);
%determines if S-expression U is a member of V at any level;
IF U=V THEN T
ELSE IF ATOM V THEN NIL
ELSE SMEMBER(U,CAR V) OR SMEMBER(U,CDR V);
Which would be in Lisp: (defun smember (u v)
"determines if S-expression U is a member of V at any level"
(cond ((equal u v) t)
((atom v) nil)
(t (or (smember u (car v))
(smember u (cdr v))))))
RLISP has been developed somewhere in the 60s/70s as a parentheses free notation for Lisp on top of Standard Lisp. Much of the computer algebra system REDUCE is written in RLISP. IF U=V THEN T
into (cond ((equal u v) t))
would seem to require an understanding of the IF construct and a mapping of infix operators to lisp functions at the least.Now, maybe this syntactic transformation has been around for decades too (the fact that I've independently toyed with the same idea suggests it's not uncommon to play with), and alternative Lisp syntaxes are quite interesting in their own right, but I do feel that the whitespace-lisp suggestion has merit in its own right (but again, I'm clearly biased). Essentially, it's an alternate syntax for s-expressions, not lisp.
This is more of a cautionary tale of going too far in making programs do 'one thing' than it is an endorsement of lisp.
What's so great about Lisp? : its extreme malleability in the way you write code and the data it uses.
Code and data are the exact same things in lisp. They are represented the same way : lists represented with braces around them who can be nested. It's called s-expressions and they are in the form (<operator> <operand1> <operand2> <operand3>). There is no fundamental difference between code and data they are just list represented as s-expressions:
(list 1 (list 2 3))
(+ 1 (+ 2 3))
Another example : (task
(time 14 00)
(log "beginning of task")
(job (backup-files (important-files-in (list-files))))
(job (delete (list-files))))
Quick, what's that above, code or data? How about both?The one nice thing about s-expressions (sexp) instead of classical curly braces is that the code written in sexp IS ITSELF the abstract syntax tree of that code.
For example, think of a function function add(a, b){return a+b;}
You could convert this function into its syntax tree like this :
(define-function (name add) (parameters a b)
(body (return (+ a b))))
If we simplify things a bit we end up with : (defun add (a b)
(+ a b))
Lo and behold, the example above IS Lisp code. Is that code or data? How about both?The syntax of Lisp is the same as its internal represention. That's called homoiconicity.
What's so great about that? Well, mix that with macros whose language is Lisp itself and can do anything with s-expressions and you end up wielding great powers.
A simple example. Let's go back to our task example. We can treat it as data :
//not actual lisp code but you get the point
var my-task = (task
(time 14 00)
(log "beginning of" )
(job (backup-files (important-files-in (list-files))))
(job (delete (list-files))))
my-task is now a list containing sub lists representing a task.
What if we did this now : //not actual lisp code
(defun time (hour minutes) (print "%d:%d" hour minutes))
(defun log (string) (print string))
//we say that task is a function
//that should call each list it contains as a function
(defun task () /*execute each list it contains*/)
//...
Now we can just do: (my-task)
What do you think is going to happen? Yes, the data, the task is being executed.Now for the last touch : add to Lisp a powerful macro system that can take any s-expression (any list) and transform it any way it see fits and you end up yielding great power. What's that language? It's Lisp itself. Code is data. Lisp code evaluting other lisp code. I am so enlightened.
Not enlightened? Didn't get anything out of my post? Then give Lisp a try! You have to dive into Lisp to be able to get it. As Eric raymond put it : "Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot." - ESR
One day, I tried explaining it to my manager, and he just couldn't get it. It wasn't clicking. Until I showed him a demo of symbolic differentiation (a la SICP), at which point he said, "Holy shit," and sat there for a few minutes considering all the implications. That was one of the greatest moments we ever shared together.
[1] Don't upvote me: https://news.ycombinator.com/item?id=7423626
http://www.paulgraham.com/avg.html
Paul's essay was the catalyst that got me to (re-)discover Lisp for myself. Scheme was taught in my CompSci I course a long time ago; but at the time, it was just a weird looking language that I forgot (CS II and beyond was all in C++ at my college).
$ cat <(echo 2) <(cat <(cat <(echo 10) <(echo 4) | +) <(echo 7)| d) | x
4
Is there any way of making that more readable? My variation of the C utility source code is here: https://gist.github.com/zokier/c55e9c9736009981b494 # 2*((10+4)/7)
$ echo 10 | add 4 | divide-by 7 | times 2
4DoSomething(an_arg, another_arg);
vs.
(DoSomething an_arg another_arg)
I'm not sure the second is markedly less readable than the first.
set foo [somefun $a $b]I've been wondering if it would be a good idea to try building a modern fish-style [1] shell aimed primarily at interactive use and one-liner expressiveness based on a Tcl interpreter. (I tried eltclsh and it's close but not quite that out of the box.)
(&(|(uid=smoyer)(uid=swm))(mail=redacted@gmail.com))
To be honest, I'm not sure why the test expressions are infix while the logical operators are prefix. My guess is that it allows a filter to be specified without whitespace.
Besides, if you want to persuade me to use Lisp, then starting by comparing the syntax to the shell is probably a bad idea, as others have said.
Well, guess what. Function name, followed by arguments, is not LISP, it's Mathematics. `A x` has meant applying a linear transformation to a vector (i.e. matrix multiplication) for a very long time.
Furthermore, saying "it's like LISP but without parenthesis around it" is like saying "it's like Java but without parenthesis around arguments and commas between then" when you actually mean to say "it's just like ML".
Finally, bash has infix operators (like `|` and `;`), which make it infinitely more readable than it would be without them. Really, if we can compare bash with any other programming language, it's ML.
∑ᵢ xᵢ
∫ x² dx
etc. And `A x` is more likely to be written as `(A x)` than `A(x)` in your example. I don't necessarily agree with the article, though...
The fact that arithmetic can be written in weird form in other languages too isn't very interesting.
One reason this is neat is that it facilitates language extensibility to a radical degree. LISP has its macros, FORTH has its compiling words. Languages that allow infix syntax have tried to come up with something similar, but I haven't personally used one that I thought was particularly successful.
Arithmetic in Lisp-style is excellent and easy to read. Thing is that programming languages infix math is ridiculously bad compared to what I can do with paper and pencil. It's really just a really bad form of imitation and to me that irks me way more than just doing it in Lisp. Math written in PL:s is hard to read in general and I'd love to see an Emacs package that lets you show an inline picture as you mark a mathematical expression of LaTeX rendering it as 'regular' math.