473,695 Members | 2,505 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python syntax in Lisp and Scheme

I think everyone who used Python will agree that its syntax is
the best thing going for it. It is very readable and easy
for everyone to learn. But, Python does not a have very good
macro capabilities, unfortunately. I'd like to know if it may
be possible to add a powerful macro system to Python, while
keeping its amazing syntax, and if it could be possible to
add Pythonistic syntax to Lisp or Scheme, while keeping all
of the functionality and convenience. If the answer is yes,
would many Python programmers switch to Lisp or Scheme if
they were offered identation-based syntax?
Jul 18 '05
699 33921
|> def posneg(filter,i ter):
|> results = ([],[])
|> for x in iter:
|> results[not filter(x)].append(x)
|> return results
|> collect_pos,col lect_neg = posneg(some_pro perty, some_file_name)

Pascal Costanza <co******@web.d e> wrote previously:
|What about dealing with an arbitrary number of filters?

Easy enough:

def categorize_excl usive(filters, iter):
results = tuple([[] for _ in len(filters)])
for x in iter:
for n, filter in enumerate(filte rs):
if filter(x):
results[n].append(x)
break
return results

Or if you want to let things fall in multiple categories:

def categorize_incl usive(filters, iter):
results = tuple([[] for _ in len(filters)])
for x in iter:
for n, filter in enumerate(filte rs):
if filter(x):
results[n].append(x)
return results

Or if you want something to satisfy ALL the filters:

def categorize_comp ose(filters, iter):
results = tuple([[] for _ in len(filters)])
for x in iter:
results[compose(filters )(x)].append(x)
return results

The implementation of 'compose()' is left as an exercise to readers :-).
Or you can buy my book, and read the first chapter.

Yours, David...

--
Keeping medicines from the bloodstreams of the sick; food from the bellies
of the hungry; books from the hands of the uneducated; technology from the
underdeveloped; and putting advocates of freedom in prisons. Intellectual
property is to the 21st century what the slave trade was to the 16th.
--
Buy Text Processing in Python: http://tinyurl.com/jskh

Jul 18 '05 #131
|> def posneg(filter,i ter):
|> results = ([],[])
|> for x in iter:
|> results[not filter(x)].append(x)
|> return results
|> collect_pos,col lect_neg = posneg(some_pro perty, some_file_name)

Pascal Costanza <co******@web.d e> wrote previously:
|What about dealing with an arbitrary number of filters?

Easy enough:

def categorize_excl usive(filters, iter):
results = tuple([[] for _ in len(filters)])
for x in iter:
for n, filter in enumerate(filte rs):
if filter(x):
results[n].append(x)
break
return results

Or if you want to let things fall in multiple categories:

def categorize_incl usive(filters, iter):
results = tuple([[] for _ in len(filters)])
for x in iter:
for n, filter in enumerate(filte rs):
if filter(x):
results[n].append(x)
return results

Or if you want something to satisfy ALL the filters:

def categorize_comp ose(filters, iter):
results = tuple([[] for _ in len(filters)])
for x in iter:
results[compose(filters )(x)].append(x)
return results

The implementation of 'compose()' is left as an exercise to readers :-).
Or you can buy my book, and read the first chapter.

Yours, David...

--
Keeping medicines from the bloodstreams of the sick; food from the bellies
of the hungry; books from the hands of the uneducated; technology from the
underdeveloped; and putting advocates of freedom in prisons. Intellectual
property is to the 21st century what the slave trade was to the 16th.
--
Buy Text Processing in Python: http://tinyurl.com/jskh
Jul 18 '05 #132


Hannu Kankaanp?? wrote:
The problem with the example arises from the fact that indentation
is used for human readability, but parens are used by the parser.
And by the editor, meaning the buggy code with the extra parens had not
been written in a parens-aware editor (or the coder had stuck a parens
on without kicking off a re-indentation).
A clash between these two representations can lead to subtle bugs
like this one. But remove one of the representations , and there
can't be clashes.


No need. Better yet, with parens you do not have to do the indentation
yourself, you just have to look at what you are typing. Matching parens
highlight automatically as you close up nested forms (it's kinda fun
actually), and then a single key chard re-indents (if you have been
refactoring and things now belong at diff indentation levels).

I used to spend a /lot/ of time on indentation (in other languages). No
more. That is just one of the advantages of all those parentheses.

kenny

Jul 18 '05 #133

Marcin 'Qrczak' Kowalczyk <qr****@knm.org .pl> writes:
The main disadvantage of macros is that they either force the syntax
to look like Lisp, or the way to present code snippets to macros is
complicated (Template Haskell), or they are as limited as C preprocessor
(which can't examine parameters).

I find the Lisp syntax hardly readable when everything looks alike,
mostly words and parentheses, and when every level of nesting requires
parens. I understand that it's easier to work with by macros, but it's
harder to work with by humans like I.


I don't understand what you're complaining about.

When you have macros such as loop that allow you to write stuff like:

(loop for color in '(blue white red)
with crosses = :crosses
collect (rgb color) into rgb-list
maximize (blue-component color) into max-blue
until (color-pleases-user color)
finally return (vlues color rgb-list max-blue))

where are the parentheses at EVERY level you're complaining about?
where is the lisp-like syntax?
Lisp is not commie-stuff, nobody forces you to program your macros
following any hypothetical party line.

--
__Pascal_Bourgu ignon__
http://www.informatimago.com/
Do not adjust your mind, there is a fault in reality.
Jul 18 '05 #134
My answer sucked in a couple ways.

(1) As Bengt Ricther pointed out up-thread, I should have changed David
Eppstein's names 'filter' and 'iter' to something other than the
built-in names.

(2) The function categorize_comp ose() IS named correctly, but it doesn't
DO what I said it would. If you want to fulfill ALL the filters, you
don't to compose them, but... well, 'all()' them:

| def categorize_join tly(preds, it):
| results = [[] for _ in len(preds)]
| for x in it:
| results[all(filters)(x)].append(x)
| return results

Now if you wonder what the function 'all()' does, you could download:

http://gnosis.cx/download/gnosis/util/combinators.py

But the relevant part is:

from operator import mul, add, truth
apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))
bools = lambda lst: map(truth, lst)
bool_each = lambda fns, args=[]: bools(apply_eac h(fns, args))
conjoin = lambda fns, args=[]: reduce(mul, bool_each(fns, args))
all = lambda fns: lambda arg, fns=fns: conjoin(fns, (arg,))

For 'lazy_all()', look at the link.

See, Python is Haskell in drag.

Yours, David...

--
Keeping medicines from the bloodstreams of the sick; food from the bellies
of the hungry; books from the hands of the uneducated; technology from the
underdeveloped; and putting advocates of freedom in prisons. Intellectual
property is to the 21st century what the slave trade was to the 16th.

Jul 18 '05 #135
Joe Marshall <jr*@ccs.neu.ed u> writes:

Alexander Schmolck <a.********@gmx .net> writes:
pr***********@c omcast.net writes: (I'm ignoring the followup-to because I don't read comp.lang.pytho n)


Well, I supposed this thread has spiralled out of control already anyway:)
Indentation-based grouping introduces a context-sensitive element into
the grammar at a very fundamental level. Although conceptually a
block is indented relative to the containing block, the reality of the
situation is that the lines in the file are indented relative to the
left margin. So every line in a block doesn't encode just its depth
relative to the immediately surrounding context, but its absolute
depth relative to the global context.
I really don't understand why this is a problem, since its trivial to
transform python's 'globally context' dependent indentation block structure
markup into into C/Pascal-style delimiter pair block structure markup.

Significantly, AFAICT you can easily do this unambiguously and *locally*, for
example your editor can trivially perform this operation on cutting a piece of
python code and its inverse on pasting (so that you only cut-and-paste the
'local' indentation). Prima facie I don't see how you loose any fine control.
Additionally, each line encodes this information independently of the other
lines that logically belong with it, and we all know that when some data is
encoded in one place may be wrong, but it is never inconsistent.
Sorry, I don't understand this sentence, but maybe you mean that the potential
inconsitency between human and machine interpretation is a *feature* for Lisp,
C, Pascal etc!? If so I'm really puzzled.
There is yet one more problem. The various levels of indentation encode
different things: the first level might indicate that it is part of a
function definition, the second that it is part of a FOR loop, etc. So on
any line, the leading whitespace may indicate all sorts of context-relevant
information.
I don't understand why this is any different to e.g. ')))))' in Lisp. The
closing ')' for DEFUN just looks the same as that for IF.
Yet the visual representation is not only identical between all of these, it
cannot even be displayed.
I don't understand what you mean. Could you maybe give a concrete example of
the information that can't be displayed? AFAICT you can have 'sexp'-movement,
markup and highlighting commands all the same with whitespace delimited block
structure.

Is this worse than C, Pascal, etc.? I don't know.
I'm pretty near certain it is better: In Pascal, C etc. by and large block
structure delimitation is regulated in such a way that what has positive
information content for the human reader/programmer (indentation) has zero to
negative information content for the compiler and vice versa. This is a
remarkably bad design (and apart from cognitive overhead obviously also causes
errors).

Python removes this significant problem, at as far as I'm aware no real cost
and plenty of additional gain (less visual clutter, no waste of delimiter
characters ('{','}') or introduction of keywords that will be sorely missed as
user-definable names ('begin', 'end')).

In Lisp the situtation isn't quite as bad, because although most of the parens
are of course mere noise to a human reader, not all of them are and because of
lisp's simple but malleable syntactic structure a straighforward replacement
of parens with indendation would obviously result in unreadable code
(fragmented over countless lines and mostly in past the 80th column :).

So unlike C and Pascal where a fix would be relatively easy, you would need
some more complicated scheme in the case of Lisp and I'm not at all sure it
would be worth the hassle (especiallly given that efforts in other areas would
likely yield much higher gains).

Still, I'm sure you're familiar with the following quote (with which I most
heartily agree):

"[P]rograms must be written for people to read, and only incidentally for
machines to execute."

People can't "read" '))))))))'.
Worse than Lisp, Forth, or Smalltalk? Yes.


Possibly, but certainly not due to the use of significant whitespace.
'as
Jul 18 '05 #136
Marco Antoniotti <ma*****@cs.nyu .edu> writes:
The best choice for code indentation in any language is M-C-q in Emacs.


You mean C-c> and C-c<.

'as
Jul 18 '05 #137
Marco Antoniotti <ma*****@cs.nyu .edu> writes:
Why do I feel like crying? :{


Could it be because you've actually got some rational argument against
significant whitespace a la python?!

'as
Jul 18 '05 #138
james anderson <ja************ @setf.de> wrote:
Matthias Blume wrote:
Most of the things that macros can do can be done with HOFs with just
as little source code duplication as with macros. (And with macros
only the source code does not get duplicated, the same not being true
for compiled code. With HOFs even executable code duplication is
often avoided -- depending on compiler technology.)

is the no advantage to being able to do either - or both - as the
occasion dictates?
I can't parse this sentence, but of course you can also use HOFs in Lisp
(all flavours). The interesting part is that most Lisp'ers don't seem
to use them, or even to know that you can use them, and use macros instead.

The only real advantage of macros over HOFs is that macros are guaranteed
to to executed at compile time. A good optimizing compiler (like GHC
for Haskell) might actually also evaluate some expressions including
HOFs at compile time, but you have no control over that.
i'd be interested to read examples of things which are better done
with HOF features which are not available in CL.


HOFs can of course be used directly in CL, and you can use macros to
do everything one could use HOFs for (if you really want).

The advantage of HOFs over macros is simplicity: You don't need additional
language constructs (which may be different even for different Lisp
dialects, say), and other tools (like type checking) are available for
free; and the programmer doesn't need to learn an additional concept.

- Dirk
Jul 18 '05 #139
Marcin 'Qrczak' Kowalczyk <qr****@knm.org .pl> writes:
I find the Lisp syntax hardly readable when everything looks alike,
mostly words and parentheses, and when every level of nesting requires
parens. I understand that it's easier to work with by macros, but it's
harder to work with by humans like I.


You find delimited words more difficult than symbols? For literate
people who use alphabet-based languages, I find this highly suspect.
Maybe readers of only ideogram languages might have different
preferences, but we are writing in English here...

--
/|_ .-----------------------.
,' .\ / | No to Imperialist war |
,--' _,' | Wage class war! |
/ / `-----------------------'
( -. |
| ) |
(`-. '--.)
`. )----'
Jul 18 '05 #140

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

220
19033
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
37
2800
by: michele.simionato | last post by:
Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the...
267
10714
by: Xah Lee | last post by:
Python, Lambda, and Guido van Rossum Xah Lee, 2006-05-05 In this post, i'd like to deconstruct one of Guido's recent blog about lambda in Python. In Guido's blog written in 2006-02-10 at http://www.artima.com/weblogs/viewpost.jsp?thread=147358
14
2175
by: Paddy3118 | last post by:
This month there was/is a 1000+ long thread called: "merits of Lisp vs Python" In comp.lang.lisp. If you followed even parts of the thread, AND previously used only one of the languages AND (and this is the crucial bit), were persuaded to have a more positive view of the other language; (deep breath, this is a long, as well as grammatically incorrect sentence), THEN WHY NOT POST ON WHAT ARGUMENTS PERSUADED YOU.
206
8317
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of the computer language Python it is claimed: \There should be one|and preferably only one|obvious...
0
9116
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8850
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8829
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5839
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4342
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4580
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2276
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1977
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.