14 ms·
Rust is surprisingly expressive
- mpweiher 13y agoGood examples: 2.days().from_now() (Rust) vs. 2.days.from_now (Ruby) I'd probably still prefer Smalltalk: 2 days fromNow. It seems to me that many distinctions we still suffer from are quite arbitrary. Yes, having numbers be objects (boxed or tagged) is one way of achieving this sort of uniform handling, but you can also achieve it statically. Just like you don't have to switch to a "scripting" language for expressive file manipulation: file:hello.world := 'Hello World!'. EDIT: typo.
- steveklabnik 13y ago> It seems to me that many distinctions we still suffer from are quite arbitrary. Agreed. And it's nice to see newer languages which bring these kinds of theoretical improvements into practical languages we as developers can actually use, rather than just as papers. I don't want to come off as anti-theory, I love theory. It's just nice to see it finally trickling down.
- mpweiher 13y agoYes, indeed. My last example is from Objective-Smalltalk [1], which straddles academia [2] and practicality [3]. The basic idea is that you really need both the practical application to show the problems and then the time to think about solutions. [1] http://objective.st http://objective.st [2] http://dl.acm.org/citation.cfm?doid=2508168.2508169 http://dl.acm.org/citation.cfm?doid=2508168.2508169, https://www.hpi.uni-potsdam.de/hirschfeld/publications/media/WeiherHirschfeld_2013_PolymorphicIdentifiersUniformResourceAccessInObjectiveSmalltalk_AcmDL.pdf https://www.hpi.uni-potsdam.de/hirschfeld/publications/media... [3] http://metaobject.com http://metaobject.com (used in most products) EDIT: added sentence about approach.
- MichaelGG 13y agoI guess we'd call these "type extensions"? F# supports this just fine, and C# can do a bit, too. Overall, I haven't found I need type extensions that much, if I have flexible function handling. It's the same level of expressiveness to write "fromNow 2 days". (fromNow having signature (int -> (int -> TimeSpan) -> DateTime). Or even "2 |> days |> fromNow" (fromNow being TimeSpan -> DateTime). Actually, this example is pretty terrible, as even C#'s basic format would be "DateTime.Now.AddDays(2)" which seems pretty fine to me - add a top-level binding for now and it's on the same level of conciseness. Also, adding type extensions to integers for time seems quite ugly. Most 3rd party libraries I've seen don't use type extensions in a graceful manner, and end up slapping members on everything and it's just silly. (And I'm ignoring the fact that using .Now in .NET is rarely correct since it's rare when you don't want to use whatever random timezone the server's configured for, instead of UTC.)
- bad_user 13y ago"2.days.from_now" is different from DateTime.Now.AddDays(2), because it can be broken in two parts: - 2.days is a duration, or a time delta, or time span, or whatever you want to call it - from_now is a method called on this duration value This construct "2.days" is useful on its own. It's actually more useful than "DateTime.Now", as durations are often part of public interfaces, whereas usage of concrete timestamps is very often hidden. The equivalent in C# for it would be "new TimeSpan(2, 0, 0, 0)". That's much more unreadable than just "2.days" and often, instead of thinking about the problem, developers fallback to specifying time spans as Ints in seconds or similar. On TimeZone, "2.days.from_now" is a timestamp. If the underlying library is not totally fucked up, like "java.util.Date" is, then it does have an attached timezone. Or in case this yields a Unix timestamp, it's really not a Unix timestamp unless it was calculated since 1970-01-01 00:00:00 UTC.
- riffraff 13y agoscala also allows, AFAIK, 2 days fromNow with the additional advantage compared to ruby/smalltalk that "days" is only available for ints in places where you import the extensions.
- stiff 13y agoI don't think the ability to write expressions similar to natural language like "2.days.from_now" should be called "expresiveness". Real expresiveness is about what SICP calls "means of abstraction" and "means of combination", not necessarily about having very nice syntax. In general I think those considerations would benefit from distinguishing a bit more between syntax and semantics. As another example, I have been doing Ruby professionally for almost 10 years now, and despite this I have to strongly disagree with the conclusion of this quotation: Python is a beautiful, clean language. But the same restrictions that make it nice and clean mean that it’s hard to write beautiful, clean libraries. Ruby, on the other hand, is a complicated, ugly language. But that complexity allows you to write really clean, nice, easy-to-use libraries. The Ruby metaprogramming magic makes for really nice syntax, which is what made me choose it over Python all those years ago, but it complicates understanding of what's going on - as I matured as an engineer, maintained a codebase over several years, several times spend long hours debugging issues coming from metaprogramming pitfalls, I shift more and more to the Python approach of building APIs in the simplest possible way, as much as possible sticking to simple function calls and no really fancy metaprogramming just to get a cleaner syntax, e.g. compare Rails has_many :foo with Django's models.ForeignKey(Foo) and the internal implementations of those. Same thing with using "BDD" testing frameworks like RSpec vs. traditional assert stuff, what is the nice syntax worth if tricky bugs hit you where you most want to avoid it, in tests. Libraries like RSpec might be "nice", but they are certainly not "easy-to-use", and I don't think I would call them quite "clean", if I look at their source code. In other words, while clean syntax is luring, in the long run clean and simple semantics is what I think is really important.
- mpweiher 13y agoI don't think it's the similarity to natural language, but rather expressing things directly. I'd agree that unconstrained metaprogramming can make code hard to read, and Ruby especially tends to go overboard. One of the goals of Objective-Smalltalk is to create a language with cleaner extensions points, making semantically consistent extension/adaptation easier. We'll see how it works out :-)
- Touche 13y agoExactly, in Rust you can't (easily) pass in a named function into a map because of all of the pointery stuff going on. Rust clearly has its uses but if you can't write high order functions then expressive it is not.
- hamburglar 13y agoSometimes I think I must be a humongous idiot because adding a "days" method to Fixnum smells like the stupidest, most counterproductive, cutesy bullshit to me, but some pretty smart folks think it's great (that's a compliment btw). Stuff like this is the opposite of expressive to me because cute expressions that read like english scream "please take a moment to analyze this and make sure it does what it sounds like." I am instantly suspicious of code that is so expressive that you can just intuit out its purpose without thinking it through. Code is too subtle for treating it that way.
- jhspaybar 13y agoThis comment makes no sense to me, you don't like how clear it is? Somehow the clarity causes you to distrust what is actually happening? Every time I have to write something like Calendar cal = Calendar.getCalendar(); cal.setDate(new Date()); cal.addDate(-2, Calendar.DAYS); Date date = cal.getDate(); I want to claw my eyes out. Is this what you consider more clear, less cutesy, somehow more productive than just 2.days.ago ?
- wheaties 13y agoHow about this 2.days.from_last_update? What does it do? What is going on with "from_last_update"? Is it actually reaching out to a database to find the last updated value? Which database? How do you configure it? All these questions and more are why you should question "english as a DSL" methods. Granted, there's a ton of great libraries out there which do this well. Take Unfiltered's handling of parsing out requests for pattern matching: case POST(Path(Seg("api" :: "calls" :: name :: Nil))) => this is "englishy" without having you scratch your head. I've also seen case POST(Path("/api/auth")) & Authenticate(user) => which then causes a DB access to happen in a configured implicit value. Now try to reason out why something is not hitting a URL or being denied when you first get into a project. Unless there's someone to explain it to you, it just happens like "magic." TL;DR How much magic do you want to deal with?
- bad_user 13y agoYour example is a sort of strawman argument, probably constructed without you being aware of it. "2.days.from_now" is indeed not free of side-effects, however "now" is a function that depends on the computer's internal clock and is generally understood what it does, the clock being a sort of global state that mutates and is generally available, whereas "2.days.from_last_update" implies usage of local mutable state, passed implicitly and highly dependent on the context you're in. Also, this example is simply wrong ... case POST(Path("/api/auth")) & Authenticate(user) => It's wrong, because this is a route matcher, so if the user is not authenticated, the server would throw an HTTP 404 Not Found status. HTTP 404 Not Found is not meant to be thrown in case the user is not authenticated. There are more relevant, more correct status codes for that, like 401 Unauthorized or 403 Forbidden, or heck, in case of classic websites, a 302 redirect to a login page is in order. So you're basically giving broken examples and calling them "magic", but the examples are obviously broken, the first one in terms of API design, the second one in terms of functionality. I really do understand your hint. But the examples you're giving are bad because they rely on totally non-obvious mutable state that's passed implicitly. This is indeed "magic", however it has nothing to do with syntactic sugar. Btw, in Scala 2.10, thanks to String interpolation, you can also construct route-matchers such as this on [1]: case POST(p"/api/calls/$name/") => Doesn't work by default, you really have to build your own stuff for this to work (see the linked example). Or if you want to throw in regular expressions, you can either do this: case POST(p"/api/calls/${Integer(id)}/") => Or you can have like a mini-DSL with regular expressions built-in: case POST(p"/api/calls/$id<\d+>/?") => // note the optional ending slash Yeah, you can do this. And it's certainly much nicer to me, more flexible and you can also make it faster than pattern-matching on Lists, as in your Unfiltered example. Is this magic? I don't see a local, mutable and implicitly-passed context, so for me it doesn't qualify. Also, whenever I see "2.days" or "4.kilobytes" in Scala code, it's certainly nicer than seeing "172800 /* 2 days in secs /" or "4096 / 4 kb */". Given that these are statically type-checked extension functions that do not modify the original Int type and that do not rely on some mutable local state passed implicitly, is this magic? My IDE doesn't think so. [1] https://github.com/alexandru/shifter/blob/master/web-api/src/test/scala/shifter/web/api/mvc/PathMatcherSuite.scala https://github.com/alexandru/shifter/blob/master/web-api/src...
- seivan 13y agoObjective-C @(2).days.fromNow; or @(2).SH_days.SH_fromNow;
- dahlberg 13y agoWhy is the string representation of: 2.months().from_now() printing a date one year in the past? date: active_support::date::Date{year: 2013, month: 2u, day: 28u}, hours: 0u, minutes: 59u, seconds: 6u, nanos: 243388962u
- jimmaswell 13y agoWhy would days be a method of an integer? It feels out of scope shoving date/time stuff into integral datatypes.
- icebraining 13y agoThat's how they do it in Ruby, but in a language with a different grammar, you could parse '2' as a different datatype depending on how it's being used. In any case, the Rust example is fairly clean, since it only injects the methods for the code that loads the Period trait.
- klibertp 13y agoThe basic idea is that objects should know how to represent themselves. In Smalltalk every Object implments writeOn: method, which gets a stream and prints self on this stream. By extension, if an object knows how to convert itself into another object, it implements a method for doing do. In Smalltalk there is a convention of putting all such methods inside "converting" protocol. For great example of how is this useful you can look at the Collection and it's subclasses in Smalltalk - all collections have many "asOtherKindOfCollection" methds, which are either inherited or implemented, depending on a collection. It's great to be able to send "asSet" to any collection that comes your way and the way Smalltalk does it is natural in purely object oriented languages. That and the fact that creating IntsToRange or StringToDayOfWeek "static" classes is actually even worse leads to the design where Integers have `to:` and `days` methods. Actually, there is one more probable cause: in Smalltalk and some other languages extending already defined types is easy, really easy, easier even than creating a new, empty class. The methods are grouped into "protocols", which are grouped into packages and it's - not quite - largely orthogonal to the classes. Combine that with powerful IDE, VC support (Monticello, Metacello) etc. and you have no reason whatsoever not to extend even the most basic classes.
- philwelch 13y agoThe question is what "2.days" actually returns. IIRC, in ActiveSupport it returns an integer number of seconds. Is that a sensible convention? If you had another class representing an span of time (with or without any absolute calendar reference) that an Integer could convert into, that might be a cleaner design. But even in that case you wouldn't necessarily have a method on Integer to confer it to a TimeSpan; you'd initialize a TimeSpan with an integer argument. In general I find it cleaner when less primitive classes can represent themselves as more or equally primitive classes, but not vice-versa. to_integer, to_float, to_list, to_boolean, etc. But on the other extreme, if your application entails establishing database connections, implementing String#to_database_connection would be ridiculous. For me, integers are much more primitive than date and time objects. `2.days` would be equivalent to implementing `2.meters` in a CAD application, but I suppose you might be OK with that. But even granting that an integer can transform itself into a representation of a time span, i.e. `2.days` is okay, `2.days.ago` is right out. That's not just an Integer representing itself as a span of time. Now all of a sudden Integer has to have knowledge and, even worse, opinions about the current date and time (which is one of the most hazardous boundary cases in all of software).
- seth1010 13y agoWhile I don't think that syntax is that important, I am fond of sugar. Because I've been working in D for a while, here's how you'd do it in D. import core.time: Duration, dur; import std.datetime: Clock, SysTime; Duration days(int number) { return dur!"days"(number); } SysTime from_now(Duration duration) { return Clock.currTime + duration; } void main() { import std.stdio: writeln; writeln(2.days.from_now); } Runnable pastebin link: http://dpaste.dzfl.pl/9b84f820 http://dpaste.dzfl.pl/9b84f820
- mcguire 13y agoI haven't really looked at D in a long time, so I'm not clear on what's going on here. Is D allowing you to write the function call "days(2)" as "2.days"? (As an aside, Nimrod allows you to do specifically that; first-arg.function-name(...) == function-name(first-arg,...).)
- mattmanser 13y agoExtension methods in C# do the same thing and have been around, what 5ish years now? Since .Net 3.5. Here's an example implementation: public static class DateExtension { public static TimeSpan Days(this int daysCount) { return new TimeSpan(daysCount, 0, 0, 0); //days, hours, mins, secs for those wondering } public static DateTime FromNow(this TimeSpan addTime) { return DateTime.Now.Add(addTime); } } usage is the same as Rust: 2.Days().FromNow(); Basically if this impresses you, you really should give modern C# a whirl as there's a lot more you can do than that. Much of how it does stuff now is how my perfect language would do it. There are bits of Ruby I love, and Rust is looking more exciting to me than Go, but the C# team really have done some amazing work.
- steveklabnik 13y agoI am certainly not implying that Rust is the only language that supports this kind of thing. Haskell is where I first saw some of this. I'm just happy that Rust is doing it well. C# is a great language, but I don't use Microsoft technology, and it's effectively Windows only.
- majorsc2noob 13y agoI run C# in production on Mac OSX, IOS and Android phones. What do you mean by Windows only?
- steveklabnik 13y agoIf you work hard enough, you can do anything. Mono is slow, doesn't support everything, and most of the help you'll get is Windows specific.
- majorsc2noob 13y agoThat is just FUD im my opinion. I havent har any issues with getting my applications working on multiple platforms. Have you har performance issues with C# on IOS?
- eranation 13y agoMy personal choice for "statically typed Ruby" is actually Scala or Kotlin. Scala has its drawbacks, especially the compile time, (which is getting better) but both have similar expressiveness when it comes to mind blowing library usage. (Although sometimes arguably in the expense of potentially complexity of the language when it comes to being able to writing such elegant libraries) I found it similar to the OP's argument regarding python vs ruby. Scala as a language might be a very subjective and divided topic, but using it with the right libraries can be very expressive just with added static typing.
- enneff 13y agoIf I read it right and the article cites the ability to add a method to the primitive number type as "expressive", then that's a pretty narrow view of expressivity. More examples would help.
- wycats 13y agoI wrote the original implementation. One thing worth noting is that the implementation isn't globally extending `uint` with `.days()`. In order to write `2.days()`, you need to first import the trait that provides the implementation. From that perspective, it's not much different from importing a function like `days_from_now` that you call as `days_from_now(2)`.
- jemeshsu 13y agoSo it is a demo that you can use Rust metaprogramming to make Rust look like Ruby. I hope this would not become idiomatic Rust.
- jimmyhmiller 13y agoIn clojure you could write this. (-> 2 days from-now) The great thing is that you don't have the weird semantic problems that the rust or ruby examples have. There are just two functions here, days and from-now.
- wycats 13y agoThat's essentially how traits work in Rust. You need to import the trait into your scope, and 2.days().from_now() is essentially sugar for days(2).from_now() where days() returns a TimeChange object.
- jimmyhmiller 13y agoDon't get wrong, rust looks fascinating. I realize that the syntax is basically sugar, but from what I understand is that you are still adding a method to a type. Here's a snippet from the code. fn days(&self) -> TimeChange { TimeChange::new().days(*self as f32) } So while you are right, it is basically sugar for days(2).from_now(), but you couldn't call the function that way. It must be attached to an instance of an uint. Also in order to get the English looking version you have to implement those function specially using traits. Whereas with the clojure version they are just normal functions, but the threading macro gives you that English readability you are looking for.
- wycats 13y agoYep! Those differences are totally correct. There are tradeoffs in each approach. One of the benefits of the Rust approach is that you can have a different implementation for each type (polymorphism), which is a feature I needed last week in some Rust code I wrote. FWIW: I believe that the Rust folks want to allow support for calling the functions directly.
- pcwalton 13y ago> So while you are right, it is basically sugar for days(2).from_now(), but you couldn't call the function that way. It must be attached to an instance of an uint. We plan to implement that, it's just not implemented yet: http://www.reddit.com/r/rust/comments/14pucx/rfc_method_call_syntax_as_sugar/ http://www.reddit.com/r/rust/comments/14pucx/rfc_method_call... > Whereas with the clojure version they are just normal functions, but the threading macro gives you that English readability you are looking for. You could do that with a macro in Rust as well. We don't make ordinary functions acquire that sugar for namespacing reasons: you can have multiple methods called e.g. "get" in scope as long as they're attached to different types, but that isn't true for functions.
- nwmcsween 13y agoI dislike all these 'expressive' or how abstract rust as a language can be from what it's trying to achieve which is to be a 'systems programming language' on par with c (c++ is not the same as c). Show the resulting assembly for both a C version and a Rust version, now map both the rust version and c version to the resulting assembly.
- copx 13y agoRust is meant to replace C++, not C. The original motivation was that the Mozilla devs were sick and tired of all the subtle ways bugs can sneak into a large, complex C++ code base. The ultimate aim is to write the nextgen browser engine not an operating system kernel or some embedded code for a system with 4kB RAM.
- steveklabnik 13y ago... though you can absolutely do the kernel stuff too.
- maninalift 13y agoThe example presented in this post is neither a great example of what Rust can do nor an elegant solution to the particular problem of dealing with dates and times. For a much further-reaching solution to this problem look at C++ user-defined literals, combined with what Bjarne Stroustrup calls "type rich programming". now() + 3days + 21s + 102ms This is not to say that c++ is the only language that can do this (although it does do it very well). See the following video for a simple overview (apologies for toe-curling introduction): http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style http://channel9.msdn.com/Events/GoingNative/GoingNative-2012... ...also the video above is worth watching just for the vector vs. list comparison.
- sklivvz1971 13y agoIn other news C# is exactly as expressive as Rust and Ruby... void Main() { Console.WriteLine(2.Days().Ago()); Console.WriteLine(4.Days().FromNow()); } //This can be a library, mmkay? public static class Extensions { public static TimeSpan Days(this int days){ return new TimeSpan(days, 0,0,0); } public static DateTime FromNow(this TimeSpan howMuch){ return DateTime.Now + howMuch; } public static DateTime Ago(this TimeSpan howMuch){ return DateTime.Now - howMuch; } } Results in: 26/12/2013 22:05:10 01/01/2014 22:05:10 Is there a better example?
- deleted 13y ago[deleted]
- mythz 13y agopublic static class Extensions { public static void Print(this object o) { Console.WriteLine(o); } } 2.Days().Ago().Print(); 4.Days().FromNow().Print();
- allochthon 13y agoStatic v. dynamic typing aside, one thing I love about Ruby is the syntactic ambiguity of a local variable versus a method call, in which parentheses are not needed.
- RodgerTheGreat 13y agoIn Factor: 2 days hence 4 weeks ago etc. http://docs.factorcode.org/content/article-calendar.html http://docs.factorcode.org/content/article-calendar.html
- quim005 13y agoReferring to "Yehuda" without any context makes this post seem like it was written for some "in-croud" as opposed to a general audience. No one is ever well known enough that you can refer to them by first name only and assume everyone else knows who you're talking about.
- stcredzero 13y agoFor the most part, I’d found the complaints about dynamic typing from the static typing camp to be very FUD-y. I very rarely get TypeErrors in my Ruby code. Refactoring generally isn’t very difficult. But slowly, this has started to change. I think that it’s that I tend to do more infrastructure and plumbing work now. I’ve run into more and more situations where types would be helpful, or picking the mutable state path has caused headaches. Explaining the attraction of dynamic debugging to static type die-hards is a lot like explaining the attractions of static typing to dynamic programming die-hards. You can only get a sense of what the other side is talking about through lots of hands-on experience. Where it's really valuable is often an edge-case, but often it's a really expensive edge-case! (Goes both ways.) This from an old Smalltalker. If you do enough Smalltalk, especially in a large established code base, you eventually see situations where you wish there were type specifications. However, you still wish that more statically compiled language people were more open minded and less knee jerk when you talk about the magic you can do. (Which also means that the open minded ones are particularly valuable.)