Max Blog

My Blog

Duck type

A few weeks ago I was watching this talk. The speaker persuaded everybody to check out Erlang. I already heard about this language because of it’s concurrency paradigms, so I thought to give it a try.

After browsing thru the specs I found an interesting construct: Pattern and Guard.

It reminded me a little of my Duck class that I wrote for BehaveAS. Th idea behind Duck was to define expectation return value in a simple internal DSL manner.
So for example I am expecting that an array will have three entries and I am only interested in second item. Or a better example when I expect an exception with a certain error id. It’s quite complicated to do this stuff without Duck :) .

Here is an example of use:

?View Code ACTIONSCRIPT
package {
  import mz.behaveas.model.ducktype.Duck;
  import flash.display.Sprite;
 
  public class DuckTypeTest extends Sprite {
    public function DuckTypeTest() {
      var a : * = 23;
      var duck : Duck = Duck.type({_type_:String, toString:"23"});
      if(!duck.equals(a)){
      	trace((duck.getReport()));
      }
      var a1 : Array = [1,2,3,"asd"];
      var duck1 : Duck = Duck.type({1:2, 3:Duck.type({_type_:String,toUpperCase:"ASD"})});
      if(!duck1.equals(a1)){
      	trace((duck1.getReport()));
      }
    }
  }
}

As you can see you can also check methods for those return values (but only if those methods doesn’t need parameters ;) ).

So back to Erlang, Pattern and Guards. I thought it would be a great idea to use Duck as a Guard for input parameters in a function.

?View Code ACTIONSCRIPT
function foo(a: Array):void{
  var matcher : Duck = Duck.type({length:3});
  if(!matcher.equals(a)){
    return;
  }
  trace(a[2]);
}

But I am not sure about performance!

posted by admin in AS3 Creative point of view,BehaveAS and have No Comments

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Before you submit form:
Human test by Not Captcha