메타 프로그래밍을위한 Python 대 Ruby
저는 현재 주로 D 프로그래머이며 D 와 같이 정적으로 컴파일 된 언어로는 수행 할 수없는 메타 프로그래밍 해킹을 지원하는 다른 언어를 내 도구 상자에 추가하려고합니다.
나는 Lisp에 대해 조금 읽었고 Lisp가하는 멋진 것들을 허용하지만 Lisp의 이상한 구문 등이없는 언어를 찾고 싶습니다. 저는 언어 전쟁을 시작하고 싶지 않으며 Ruby와 Python 모두 장단점이 있다고 확신하므로 개인적으로 중요한 사항을 나열하겠습니다. Ruby, Python 또는 다른 언어가 나에게 가장 적합한 지 알려주세요.
중대한:
- 좋은 메타 프로그래밍. 런타임에 클래스, 메서드, 함수 등을 생성하는 기능. 가급적이면 코드와 데이터 사이의 최소한의 구분, Lisp 스타일.
- 훌륭하고 깔끔하며 건전한 구문과 일관되고 직관적 인 의미 체계. 기본적으로 신중하고 사용하기 쉽고 현대적인 언어입니다.
- 다중 패러다임. 모든 프로젝트에 적합한 패러다임은 없으며 프로젝트 내의 모든 작은 하위 문제까지도 적합하지 않습니다.
- 프로그래밍에 대해 생각하는 방식에 실제로 영향을 미치는 흥미로운 언어입니다.
다소 중요 :
- 공연. 성능이 괜찮 으면 좋겠지 만 성능이 진짜 우선이라면 D를 대신 사용하겠습니다.
- 잘 기록 된.
중요하지 않음 :
- 커뮤니티 규모, 라이브러리 가용성 등. 이들 중 어느 것도 언어 자체의 특성이 아니며 모두 매우 빠르게 변경 될 수 있습니다.
- 직업 가용성. 저는 풀 타임 전문 프로그래머가 아닙니다. 나는 대학원생이고 프로그래밍은 내 연구와 밀접한 관련이 있습니다.
- 백만 명의 코드 원숭이를 염두에두고 작업 한 대규모 프로젝트로 주로 설계된 모든 기능.
적어도 이데올로기 적 수준에서 파이썬과 루비 사이에는 큰 차이가 없습니다. 대부분의 경우 동일한 맛의 다른 맛일뿐입니다. 따라서 어떤 것이 귀하의 프로그래밍 스타일과 더 일치하는지 확인하는 것이 좋습니다.
나는 Lisp에 대해 조금 읽었고 Lisp가하는 멋진 것들을 허용하지만 Lisp의 이상한 구문 등이없는 언어를 찾고 싶습니다.
우리 모두는 아닐까요.
코드와 데이터의 최소한의 차이, Lisp 스타일
안타깝게도 코드와 데이터 사이의 최소한의 차이와 "이상한"구문은 서로의 결과입니다.
읽기 쉬운 구문을 원한다면 Python이 있습니다. 그러나 코드는 일반적으로 사용되는 내장 데이터 구조로 표시 되지 않습니다 . 대부분의 언어가 그렇듯이 '중요'목록의 항목 # 1에서 실패합니다. 따라서 유용한 도움을 제공하기가 어렵습니다.
모든 것을 가질 수는 없습니다. 이 생각을 한 사람은 당신이 처음이 아닙니다. 당신의 이상적인 언어와 같은 것이 존재한다면 우리는 모두 그것을 사용하고있을 것입니다. 현실 세계는 당신의 이상에 미치지 못하기 때문에 위시리스트의 우선 순위를 다시 지정해야합니다. "중요"섹션은 당신에게 정말로 중요한 것이 무엇인지 식별하기 위해 다시 정렬 되어야합니다.
솔직히, 메타 프로그래밍 기능에 관한 한 Ruby와 Python은 일부 지지자들이 인정하는 것보다 훨씬 더 유사합니다. 두 언어에 대한이 리뷰는 꽤 좋은 비교 / 리뷰를 제공합니다.
따라서 몇 가지 기준에 따라 하나를 선택하십시오. Rails를 좋아하고 그 코드를 공부하고 싶을 수도 있습니다. 아마도 SciPy가 당신의 것입니다. 도서관, 커뮤니티 등의 생태계를 살펴보고 하나를 선택하십시오. 어느 쪽을 선택했는지에 따라 메타 프로그래밍의 열반을 잃지 않을 것입니다.
면책 조항 : 저는 두 언어 중 하나만 사용하지만, 둘 다에 최소한 작은 작업 프로그램 (Perl, bash 또는 GNU make를 사용하는 빠른 스크립트가 아닌)을 작성했습니다.
Ruby는 도메인 별 언어를 쉽게 만들 수 있도록 열심히 작동하기 때문에 "다중 패러다임"포인트 3에 정말 좋을 수 있습니다. 예를 들어, 온라인으로 검색하여 Ruby on Rails 코드 몇 비트와 Rake 코드 몇 비트를 살펴보십시오. 둘 다 Ruby이고 유사점을 볼 수 있지만 일반적으로 동일한 언어로 생각하는 것과 같지 않습니다.
파이썬은 나에게 조금 더 예측 가능해 보이지만 (아마도 '깨끗한'및 '정상적인'포인트 2와 관련이 있음), 그것이 언어 자체 때문인지 아니면 일반적으로 다른 값을 가진 사람들이 사용하는지 여부는 실제로 알 수 없습니다. . 저는 파이썬에서 깊은 마법을 시도한 적이 없습니다. 나는 확실히 두 언어 모두 잘 생각하고 있다고 말할 것입니다.
Both score well in 1 and 4. [Edit: actually 1 is pretty arguable - there is "eval" in both, as common in interpreted languages, but they're hardly conceptually pure. You can define closures, assign methods to objects, and whatnot. Not sure whether this goes as far as you want.]
Personally I find Ruby more fun, but in part that's because it's easier to get distracted thinking of cool ways to do things. I've actually used Python more. Sometimes you don't want cool, you want to get on with it so it's done before bedtime...
Neither of them is difficult to get into, so you could just decide to do your next minor task in one, and the one after that in the other. Or pick up an introductory book on each from the library, skim-read them both and see what grabs you.
Have you considered Smalltalk? It offers a very simple, clear and extensible syntax with reflectivity and introspection capabilities and a fully integrated development environment that takes advantage of those capabilities. Have a look at some of the work being done in Squeak Smalltalk for instance. A lot of researchers using Squeak hang out on the Squeak mailing list and #squeak on freenode, so you can get help on complex issues very easily.
Other indicators of its current relevance: it runs on any platform you'd care to name (including the iPhone); Gilad Bracha is basing his Newspeak work on Squeak; the V8 team cut their teeth on Smalltalk VMs; and Dan Ingalls and Randal Schwartz have recently returned to Smalltalk work after years in the wilderness.
Best of luck with your search - let us know what you decide in the end.
Lisp satisfies all your criteria, including performance, and it is the only language that doesn't have (strange) syntax. If you eschew it on such an astoundingly ill-informed/wrong-headed basis and consequently miss out on the experience of using e.g. Emacs+SLIME+CL, you'll be doing yourself a great disservice.
Your 4 "important" points lead to Ruby exactly, while the 2 "somewhat important" points ruled by Python. So be it.
You are describing Ruby.
- Good metaprogramming. Ability to create classes, methods, functions, etc. at runtime. Preferably, minimal distinction between code and data, Lisp style.
It's very easy to extend and modify existing primitives at runtime. In ruby everything is an object, strings, integers, even functions.
You can also construct shortcuts for syntactic sugar, for example with class_eval.
- Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language.
Ruby follows the principle of less surprise, and when comparing Ruby code vs the equivalent in other language many people consider it more "beautiful".
- Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project.
You can follow imperative, object oriented, functional and reflective.
- An interesting language that actually affects the way one thinks about programming.
That's very subjective, but from my point of view the ability to use many paradigms at the same time allows for very interesting ideas.
I've tried Python and it doesn't fit your important points.
Compare code examples that do the same thing (join with a newline non-empty descriptions of items from a myList
list) in different languages (languages are arranged in reverse-alphabetic order):
Ruby:
myList.collect { |f| f.description }.select { |d| d != "" }.join("\n")
Or
myList.map(&:description).reject(&:empty?).join("\n")
Python:
descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
Or
"\n".join(f.description() for f in mylist if f.description())
Perl:
join "\n", grep { $_ } map { $_->description } @myList;
Or
join "\n", grep /./, map { $_->description } @myList;
Javascript:
myList.map(function(e) e.description())
.filter(function(e) e).join("\n")
Io:
myList collect(description) select(!="") join("\n")
Here's an Io guide.
Ruby would be better than Lisp in terms of being "mainstream" (whatever that really means, but one realistic concern is how easy it would be to find answers to your questions on Lisp programming if you were to go with that.) In any case, I found Ruby very easy to pick up. In the same amount of time that I had spent first learning Python (or other languages for that matter), I was soon writing better code much more efficiently than I ever had before. That's just one person's opinion, though; take it with a grain of salt, I guess. I know much more about Ruby at this point than I do Python or Lisp, but you should know that I was a Python person for quite a while before I switched.
Lisp is definitely quite cool and worth looking into; as you said, the size of community, etc. can change quite quickly. That being said, the size itself isn't as important as the quality of the community. For example, the #ruby-lang
channel is still filled with some incredibly smart people. Lisp seems to attract some really smart people too. I can't speak much about the Python community as I don't have a lot of firsthand experience, but it seems to be "too big" sometimes. (I remember people being quite rude on their IRC channel, and from what I've heard from friends that are really into Python, that seems to be the rule rather than the exception.)
Anyway, some resources that you might find useful are:
1) The Pragmatic Programmers Ruby Metaprogramming series (http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming) -- not free, but the later episodes are quite intriguing. (The code is free, if you want to download it and see what you'd be learning about.)
2) On Lisp by Paul Graham (http://www.paulgraham.com/onlisp.html). It's a little old, but it's a classic (and downloadable for free).
I am using Python for many projects and I think Python does provide all the features you asked for.
important:
- Metaprogramming: Python supports metaclasses and runtime class/method generation etc
- Syntax: Well thats somehow subjective. I like Pythons syntax for its simplicity, but some People complain that Python is whitespace-sensitive.
- Paradigms: Python supports procedural, object-oriented and basic functional programming.
- I think Python has a very practical oriented style, it was very inspiring for me.
Somewhat important:
- Performance: Well its a scripting language. But writing C extensions for Python is a common optimization practice.
- Documentation: I cannot complain. Its not that detailed as someone may know from Java, but its good enough.
As you are grad student you may want to read this paper claiming that Python is all a scientist needs. Unfortunately I cannot compare Python to Ruby, since I never used that language.
Regards, Dennis
@Jason I respectively disagree. There are differences that make Ruby superior to Python for metaprogramming - both philosophical and pragmatic. For starters, Ruby gets inheritance right with Single Inheritance and Mixins. And when it comes to metaprogramming you simply need to understand that it's all about the self. The canonical difference here is that in Ruby you have access to the self object at runtime - in Python you do not!
Unlike Python, in Ruby there is no separate compile or runtime phase. In Ruby, every line of code is executed against a particular self object. In Ruby every class inherits from both object and a hidden metaclass. This makes for some interesting dynamics:
class Ninja
def rank
puts "Orange Clan"
end
self.name #=> "Ninja"
end
Using self.name accesses the Ninja classes' metaclass name method to return the class name of Ninja. Does metaprogramming flower so beautiful in Python? I sincerely doubt it!
Well, if you don't like the lisp syntax perhaps assembler is the way to go. :-)
It certainly has minimal distinction between code and data, is multi-paradigm (or maybe that is no-paradigm) and it's a mind expanding (if tedious) experience both in terms of the learning and the tricks you can do.
Io satisfies all of your "Important" points. I don't think there's a better language out there for doing crazy meta hackery.
one that supports the metaprogramming hacks that just can't be done in a statically compiled language
I would love to find a language that allows some of the cool stuff that Lisp does
Lisp can be compiled.
Did you try Rebol?
My answer would be neither. I know both languages, took a class on Ruby and been programming in python for several years. Lisp is good at metaprogramming due to the fact that its sole purpose is to transform lists, its own source code is just a list of tokens so metaprogramming is natural. The three languages I like best for this type of thing is Rebol, Forth and Factor. Rebol is a very strong dialecting language which takes code from its input stream, runs an expression against it and transforms it using rules written in the language. Very expressive and extremely good at dialecting. Factor and Forth are more or less completely divorced from syntax and you program them by defining and calling words. They are generally mostly written in their own language. You don't write applications in traditional sense, you extend the language by writing your own words to define your particular application. Factor can be especially nice as it has many features I have only seen in smalltalk for evaluating and working with source code. A really nice workspace, interactive documents, etc.
There isn't really a lot to separate Python and Ruby. I'd say the Python community is larger and more mature than the Ruby community, and that's really important for me. Ruby is a more flexible language, which has positive and negative repercussions. However, I'm sure there will be plenty of people to go into detail on both these languages, so I'll throw a third option into the ring. How about JavaScript?
JavaScript was originally designed to be Scheme for the web, and it's prototype-based, which is an advantage over Python and Ruby as far as multi-paradigm and metaprogramming is concerned. The syntax isn't as nice as the other two, but it is probably the most widely deployed language in existence, and performance is getting better every day.
If you like the lisp-style code-is-data concept, but don't like the Lispy syntax, maybe Prolog would be a good choice.
Whether that qualifies as a "fun to use, modern language", I'll leave to others to judge. ;-)
Ruby is my choice after exploring Python, Smalltalk, and Ruby.
What about OCaml ?
OCaml features: a static type system, type inference, parametric polymorphism, tail recursion, pattern matching, first class lexical closures, functors (parametric modules), exception handling, and incremental generational automatic garbage collection.
I think that it satisfies the following:
Important:
- Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language.
- Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project.
- An interesting language that actually affects the way one thinks about programming.
Somewhat important:
- Performance. It would be nice if performance was decent, but when performance is a real priority, I'll use D instead.
- Well-documented.
I've use Python a very bit, but much more Ruby. However I'd argue they both provide what you asked for.
If I see all your four points then you may at least check: http://www.iolanguage.com/
And Mozart/Oz may be interesting for you also: http://mozart.github.io/
Regards Friedrich
For python-style syntax and lisp-like macros (macros that are real code) and good DSL see converge.
I'm not sure that Python would fulfill all things you desire (especially the point about the minimal distinction between code and data), but there is one argument in favour of python. There is a project out there which makes it easy for you to program extensions for python in D, so you can have the best of both worlds. http://pyd.dsource.org/celerid.html
if you love the rose, you have to learn to live with the thorns :)
I would recommend you go with Ruby.
When I first started to learn it, I found it really easy to pick up.
Do not to mix Ruby Programming Language with Ruby Implementations, thinking that POSIX threads are not possible in ruby.
You can simply compile with pthread support, and this was already possible at the time this thread was created, if you pardon the pun.
The answer to this question is simple. If you like lisp, you will probably prefer ruby. Or, whatever you like.
I suggest that you try out both languages and pick the one that appeals to you. Both Python and Ruby can do what you want.
Also read this thread.
Go with JS just check out AJS (Alternative JavaScript Syntax) at my github http://github.com/visionmedia it will give you some cleaner looking closures etc :D
Concerning your main-point (meta-programming): Version 1.6 of Groovy has AST (Abstract Syntax Tree) programming built-in as a standard and integrated feature. Ruby has RubyParser, but it's an add-on.
참고URL : https://stackoverflow.com/questions/144661/python-vs-ruby-for-metaprogramming
'Programing' 카테고리의 다른 글
Vim-vim을 시작할 때 즉시 명령을 실행하는 방법은 무엇입니까? (0) | 2020.09.07 |
---|---|
apt-get : 명령을 찾을 수 없습니다. (0) | 2020.09.07 |
편집기에 기본 유형이 없습니다. (0) | 2020.09.07 |
PHP에서 내 웹 사이트의 모든 쿠키를 삭제하는 방법 (0) | 2020.09.07 |
왜“우리”와“자신”의 의미가 git-svn으로 바뀌 었습니까? (0) | 2020.09.07 |