bakkdoor / fancy

Fancy is a dynamic, object-oriented programming language inspired by Smalltalk, Ruby, Io and Erlang that runs on the Rubinius VM.
http://www.fancy-lang.org
BSD 3-Clause "New" or "Revised" License
261 stars 22 forks source link

Forwarding methods / "Optional arguments" #36

Closed bakkdoor closed 14 years ago

bakkdoor commented 14 years ago

This idea came to my mind when writing some test code in fancy: Often, especially in case of constructor methods, we'd like to have "optional" arguments. Since this isn't possible due to how fancy's syntax works, we have to define several methods, that simply forward to a more generalized method. For example:

class Person {
  def initialize: name {
    initialize: name age: 23 city: "Osnabrück" # default age is 20 and city is Osnabrück
  }

  def initialize: name age: age {
    initialize: name age: age city: "Osnabrück"
  }

  def initialize: name age: age city: city {
    @name = name
    @age = age
    @city = city
  }
  ...
}

As you can see, we're kind of "overloading" the consructor methods. It would be nice, imho, to allow some kind of syntax for doing this automatically.

For example:

class Person {
  def initialize: name age: age = 23 city: city = "Osnabrück" {
    @name = name
    @age = age
    @city = city
  }
}

Would do the same, as the code above. It would basically define all the necessary methods and automatically forward to the more general method from within the specialized ones. Semantically, the latter code would be the same as the first first, but less typing.

Comments?

vic commented 14 years ago

Yeah, that's something we really need.

Your syntax proposal reminds me a little bit of what ooc does, hehe I like what you say, I'd just maybe extend it to automatically assign to instance variables (if the variable identifier starts with @, iirc ooc does something like that) .. we could also get rid of the = sign.

  def initialize: @name age: @age 23 city: @city "Raccoon" {
      # Much less typing as we don't need to type
      # @foo = foo .. @bar = bar
  }
vic commented 14 years ago

So here's my +1 vote for this. We just need to settle down the syntax.

bakkdoor commented 14 years ago

Ok, like the syntax without the "=". Also, having "@" to indicate, to autmatically assign to instance vars makes sense, too. Less typing is almost always good ;)

NilsHaldenwang commented 14 years ago

Yeah, nice idea, I like this! Go for it! :-)

vic commented 14 years ago

I'm implementing this.

Removing the "=" seems to cause parser conflicts, so I'm leaving the "=" by now..

bakkdoor commented 14 years ago

Ok, whatever makes it work for now. We can always improve stuff when we need to ;)

bakkdoor commented 14 years ago

implemented.