HaXe Demonstration
Posted on June 18, 2009
I recently gave a presentation on haXe at the Strands offices in Corvallis and Seattle. I think it raised a few eyebrows, but probably ended up raising more questions than it answered. This was to be expected, as haXe is pretty unique in its ability to target multiple web-related platforms. The devil is in the details, and so I thought it was best to post everything here on the blog so that interested individuals can go over the specifics in a more involved way.
The demo that I showed was actually two parts: A simple “hello world” trace example, which I compile to swf, php, and javascript. Then, a more complex example that compiles some code to each of those targets, and then uses conditional compilation to build a web page that displays output from each target all at once (The PHP target references the javascript source, a javascript method references the swf file).
This, to me, is perhaps the most satisfying aspect of haXe: The ability to treat each target as a minor variation of an API, rather than as a set of totally unrelated platforms. Developing, targetting, and displaying results simultaneously is a strange feeling. All of a sudden, javascript, php, and swf are operating off of the same script, and you are totally in control.
You can download the source as an archive here, or browse the source here. Once you compile the Demo2 file, you should see something like this.
There’s a README in the source that’ll explain what’s going on.
If you’re totally new to haXe, you’ll want to download the compiler from the haxe.org download page. After installing, you can run the build1.hxml - build4.hxml examples by simply typing in:
haxe build1.hxml
For each of the build files. For the build.hxml file (non-numbered), you will need to edit it so that it points and outputs to a working web folder. If you use TextMate, you can download the textmate bundle for haXe, and use the editor to browse and build files.
Filed Under haXe
Leave a Comment
Injecting Methods into HaXe with “using”
Posted on May 23, 2009
Nicolas just added a new keyword to the haXe compiler called “using”. In short, this keyword lets you inject additional methods into instances of Types.
“using” explained
The haXe “using” keyword is essentially behaving like a type of mixin, but it’s different than other types of mixins, such as those implemented by Ruby. Explaining things in words is tricky, so here’s some example code. First, we’ll implement something without “using”:
// in Demo.hx
class Demo{
public static function main(): Void
{
trace(BarStringClass.addBar('foo'));
}
}
//in BarStringClass.hx
class BarStringClass{
public static function addBar(str:String) :String
{
return str + ' bar';
}
}
If we compile the code using main() from Demo, we’ll get “foo bar”. We’re simply using the static class from BarStringClass to process the string and tracing it. Pretty simple. Now let’s look at what we can do to Demo.hx with “using”:
//in Demo.hx
using BarStringClass;
class Demo{
public static function main(): Void
{
trace('foo'.addBar());
}
}
haXe now lets us access BarStringClass static functions as if they were functions of the String Class. In this fashion, the standard base classes can be augmented with additional methods without the need to extend them explicitly.
Notice how in this example it wasn’t even necessary to specify the “str:String” argument required by addBar(). When the haXe compiler injects the methods from BarStringClass, it will automatically fill in the current instance as the first argument… turning BarStringClass.addBar(’foo’) into ‘foo’.addBar(). All of the first argument Types of the “using” classes will be augmented in this way.
So in this case, BarStringClass had one static function (addBar), and the first argument type was String. Therefore, every String instance now gets the addBar() function. You could have many different Static functions in a “using” class, and each of the first argument classes will get injected in the same way.
“using” with types and/or classes
The other nice thing about this approach is that it works with the more broadly defined Types/typedefs, and not just Classes. So, my IterTools functions that work (mainly) with Iterable Types can be injected with “using”, and then you can do things like:
for ( i in [1,2,3,4].cycle(5) ){
trace(i);
}
…to iterate through the numbers 1 through 4 five times. “cycle()” and the rest of the functions that operate on Iterables would also then work with Lists, FastLists, Hashes, and so forth. When you add “using IterTools;” at the top of a class file, anything that can iterate can now “cycle()”.
Caveats
There are two significant caveats with “using”. The first is that the injected methods are not available through reflection. This means they’re not part of the “run-time” class instance. The second caveat is that it can be very easy to overload several instances of a single method name (from multiple “using” classes). Currently, haXe’s behavior is to only use the first matching static method from a “using” Class.
“using” can be habit forming
Some of the positives to the “using” keyword approach are:
- You can manage classes externally from code that defines them, seamlessly adding in functionality by augmenting classes and typedefs.
- Anything you can do through the “using” keyword can be done by using Static Classes, so there is very little ‘magic’ going on… just some clever reformatting of function calls.
- There’s a ton of Static classes out there (in addition to my own) that already contain a lot of good practical functionality. You can easily reuse these classes as “using” classes, or write your own that handle specific needs.
- Method completion works with –display. So once you include the “using” keyword with an appropriate class, you can instantly see the extra available methods by triggering a code-completion request inside your editor (assuming the editor does –display code completion).
I’m assuming “using” will be added in the next version of haXe (2.04). Till then, you can play around with it by downloading and building from the CVS sources.
Filed Under haXe
Leave a Comment
Tim Ferriss and the 4 Hour Work Week
Posted on May 10, 2009
So, there’s this Tim Ferriss guy that’s some kind of productivity guru. He’s written a book called “The 4 Hour Work Week” which gives you tips on how to streamline the amount of “work” that you do in a day.
In the interest of self disclosure, I didn’t read the book, because I tend to be more interested in what people do than what they say to do. The cliff notes versions I’ve seen on line seem to imply that he has rediscovered the Pareto Principle, or the incredibly well worn 80/20 rule, along with a host of other efficiency principles that seem incredibly hackneyed. I’m not sure what his unique twist is, maybe he’s good at telling stories.
It turns out Tim’s claim to fame is that he’s gotten very good at finding success in niche activities on technicalities, and then marketing the hell out of them.
- He’s a Chinese Kickboxing champion, which he achieved by shoving the smaller opponents out of the ring, and winning through their disqualification.
- He’s an expert at Argentine tango, where he has set a record for spinning. This isn’t really a technical feat, it was more of a novelty act for the Kelly Ripa show.
- He lectures at Princeton’s electrical engineering group (on entrepreneurship).
I think that very few people can actually benefit from what he talks about, mainly because he proposes “outsourcing” minute details of daily planning (to personal assistants in India… seriously!). I don’t know if he’s thought about marketing his book in India (who would they outsource to?). He also is against liberal use of cell phones and e-mail.
I want to mark this up as another “the secret to success is selling secrets to success” type of situations. I could care less about yet another productivity guide, I’d rather hear about how he was able to network and promote himself. That seems to be something he actually knows a thing or two about. From what I hear, his self promotion drive irked a lot of people, and certainly took much more than 4 hours a week. However, I have to hand it to him, it seems to have been very successful.
Filed Under General Observation, Manipulation
2 Comments
Duck Typing and “Roles”, Continued
Posted on May 7, 2009
My previous article talked a bit about Perl’s new “roles” method for managing typing. In the article, I tried to address some of the criticism levied against duck typing, and in doing so perhaps misrepresented Perl Roles as being “rigid”.
Another blogger by the name of Sam Crawley gives an overview of the way that roles provide more flexibility in a recent post, however there is still a significant difference in approaches.
Duck Typing and Reflection
In both the original post on duck types and Perl Roles, as well as Sam’s rebuttal of my previous article, there is mention of the “can” method. This method is used like:
$dog_or_tree->can( 'bark' );
This method tests to see if an object has the requisite field (presumably so that you can call a corresponding method, or access a property), and is very similar to the intent of duck typing. However, it’s important to note that using this “can” method is not the same as duck typing. The method is actually what’s known as a runtime class reflection, and not a compile-time type check. This is an important distinction, because true duck-typing will make the compiler check the types once before compilation, while reflection requires that the types be checked every time the code is run. On many platforms (VM’s such as Adobe’s AVM2) reflection calls are quite slow, and should be avoided.
It seems that both authors are conflating these approaches, and unfairly criticizing duck typing for the inefficiencies of managing types through reflection:
If you want to get stricter, and if your language supports this, you can even check the arity or types of the allowed signatures of the method — but look at all of the boilerplate code you have to write to make this work. That’s also code to check only a single method.
You don’t need to insert “boilerplate code” in your classes for conventional duck typing approaches. You write one “typedef” of required methods, as in a haXe example:
typedef Duck ={
function walks(location:Position, direction:Vector<Float>):Waddle<Step>;
function talks(say:String):Quack<Sound>;
}
And typically put it somewhere in your compiler class path. Now you can accept “Ducks” as arguments anywhere, and they can be checked by the compiler. From a typedef, we can assert that the Duck walks and talks appropriately (producing “Waddle” and “Quack” collections of “Steps” and “Sounds”). The arity, return, and argument types let us describe the behavior in great detail. The level of discrimination that is available only depends on the specificity of the classes, and any duck type assertions occur externally to class specific code. After we write our Main classes, and create the Duck typedef, we could perhaps differentiate between different ducks, such as those that “molt() : Void”, and we wouldn’t need to update any existing class code outside of creating a new typedef:
typedef MoltingDuck = {
> Duck,
function molt():Void
}
Now we can make sure we’re dealing with molting ducks, that behave exactly like ducks in every other way.
Roles vs. Duck Typing, revisited
However, for a final comparison of Roles and Duck Typing, it is perhaps fair to say that Roles are more powerful in a sense. Roles actually cover a lot of ground, it’s just different ground than what Duck Typing covers. Roles encompass two major forms of class specification: interfaces and mixins. The former lets you define methods and properties that must be implemented by the host class, while the latter define methods and properties that are implemented by the Role itself (the methods are specified in the Role description) In this way, you can even use Roles as building blocks for class functionality in lieu of inheritance. It seems that this is a pretty revolutionary way to approach OOP, so more power to them.
However, the type checking performed by Roles is more rigid and structured than duck typing, at least in terms of what happens at the compiler level. You still must declare a Role inside of a class description (a la interfaces) for compile time checking. For interpreted languages, it may not be that important to distinguish between type checking that occurs at the compiler vs. the checks that occur at run-time. However, this distinction can be very important for other languages.
I can appreciate the need for articles to promote the idea of Roles within and without the Perl community, but I think it can also be done without unfairly criticising other approaches. Despite the inaccuracies, the discussion of Roles has gotten me interested in Perl again, and nothing else has done that in years.
Duck Typing and “Roles” in Object Oriented Programming
Posted on May 5, 2009
Update: I have a more recent post on this subject here.
I recently read an article talking about the new “roles” system in Perl. Roles are classes of objects that perform the same set of functions. So, if you had an “Eagle” object, or a “Sparrow” object, perhaps both would have the field “feathers”, and the function “fly”. Each object might then differ in the size of the beak, or maybe only the Eagle has the method “swoop”. Perl roles would let you tag a collection of methods (in this case, “feathers” and “fly”) as performing a certain role (in this case, probably “flying_bird”). This is pretty useful, because if you wanted to write a (simple) bird watching simulator, you could handle any type of bird object as long as it handled that method and that property. If the method names are slightly different (for instance, perhaps the “Condor” object has the method “soar” instead of “fly”), but behave the same, Roles can resolve this.
Know Your Role
Perl’s role system is in contrast to duck typing that I use a lot in haXe. Duck typing skips the process of setting up explicit roles, and just tries to match the field/method names explicitly. So, any object that can “fly” and has “feathers” can be considered as a “flying bird” without the need of declaring roles in each object. The matching parameters for a duck type are typically given in a typedef, which is just a list of field names and types.
The article states that roles have the following advantages:
- Roles are explicitly given for classes… in their case they use the example of a field “bark”, which might belong to a “tree” or a “dog” object… duck typing perhaps could confuse them. Roles would not.
- Roles are more flexible… you have more fine grained control over what constitutes or is compatible with a role.
Better Examples
However, I’m not sold. The example they give (”bark” belonging to both “trees” and “dogs”) is not a good one. “Tree bark” seems like it would be a property, while “Dog bark” seems like it would be a method/action. This could easily be detected by most duck type checking languages, and would clear up a great deal of field naming confusion right away.
The “old cliché” that they reference (if it walks like a duck, and talks like a duck, then it is a duck) actually gives a better example. In this case, duck typing is occurring on two fields, rather than one. The chances that classes have two fields that are identically named, yet pertain to unrelated objects is much lower. In the article they say that “roles add context back”, but I would argue that context can get added back by being more specific with typedefs.
Using Natural Language Instincts
This ability to manage specificity through the selection and addition of representative symbols is an integral part of our natural language abilities. We use it every time we need to search the web (If I wanted to specify that I’m looking for dog-like bark things, I might query “bark woof”, rather than just “bark”. The specification is only as complex as it needs to be, and it relies on human knowledge to decide which terms best describe/discriminate the necessary object properties. It also doesn’t rely on specifically describing the roles beforehand, or explicitly indicate which objects perform which role. Duck typing does rely on programmers to differentiate their classes semantically through field names, which I consider good coding practice (i.e. don’t have two fundamentally different classes that have the same field names, and don’t have similar classes with completely different field names).
In the end, it boils down to managing complexity. Perl roles will force you to specify all of your roles explicitly, and require that appropriate object class code indicate a role behavior where necessary. This is “bad” complexity imho, since it involves a lot of boilerplate and class code markup. On the other hand, duck typing will force you to be very careful and specific with how you define a typedef, and occasionally force you to change how fields are named. In certain cases, it might keep you from treating certain classes as related when necessary, or it might confuse two unrelated classes… all on the basis of whether fields match or not.
Managing Type Context with Duck Typing
Certain duck type situations can cause false-negative or false-positive typing conflicts:
- Classes should have the same basic typedef, but have mismatched field names (false-negative typing): This is usually the result of bad coding style for the classes. Use this as an opportunity to rename the mismatched field names to something more consistent. Sometimes getter/setter mechanisms interfere with a field match. If one class uses a getter/setter for a property field, consider adopting the same behavior on the other class.
- Classes are not related, but the typedef selects both of them (false positive typing): See if there’s another field that can be added to the duck type check. Usually this will let you discriminate between the two classes.
There still could be certain situations where duck typing fails, and in these cases, I typically fall back on class reflection and other methods to get things working. However, these cases are very rare for me.
In conclusion, both approaches have drawbacks, but I find that duck typing allows me to handle complexity in more familiar natural language terms, while roles are more rigid and top-down. The former is better if I’m working on my own projects, but perhaps roles really shine when you have to work with larger classes that you don’t have control over or want to modify extensively.
I’m surprised that Perl went with such a strong top-down approach for determining object class types. It really seems to go against its loosely-styled ad-hoc nature. Perl has become somewhat stagnant in recent years, so perhaps this is an attempt to shake things up a bit. If so, I have doubts whether it’s a step in the right direction.
Filed Under Design, General Observation, haXe
3 Comments
Cognitive Phase Points in Social Network Sizes
Posted on April 25, 2009
Social networking has been a huge buzzword for the last few years. Companies have sprung up around helping people keeping in touch with friends, family, colleagues, and potential colleagues in a semi-public, semi-permanent format. In typical “buzzword” fashion, social networking has been mercilessly exploited and shoehorned into dozens of contrived contexts. Whether it’s Walmart trying to set up a social network for teens… who perhaps didn’t want to associate with the Walmart aesthetic, or iYomu, which tried to cater to an older demographic… typically the slowest population to adapt to new technology, particularly new communication technology.
In addition to assuming that social networks can be applied to nearly any business endeavor, there was also the sense that a greater utilization of these networks would somehow improve some sort of social awareness, and by corollary, provide the participating users with greater ‘access’ to individuals in otherwise inaccessible or distant locations.
To a certain degree, this is true. People can keep tabs on distant friends, families, and colleagues in very informal fashion using facebook and twitter, but there has to be limits to how many meaningful social connections an individual can maintain, at a minimum level of awareness…
The general sense seems to be that “more friends=better”, and entire careers seem to have been built on exploiting social networks for self promotion. However, turning your personal social network into a competitive ‘numbers game’ seems… well… wrong. It turns out there are pretty well defined ‘averages’ for how many meaningful relationships an individual can maintain. Basically, there are three thresholds for social connections.
- 5 individuals = A number influenced by our working short term memory. This seems to be the maximum level of individuals that you can become ‘intimately familiar’ with. You might be able to predict how this individual would respond to given situations, or finish their sentences for them.
- 15 individuals = The maximum number of individuals you can form a “deep trust” with. These are individuals that you feel completely relaxed and unguarded around.
- 150 individuals = The maximum number of individuals you can “enumerate” and identify with in a meaningful fashion.
The 150 number is a far cry from the thousands of friends on facebook/myspace that many people seem driven to acquire. In fact, the very act of ‘friending’ someone on facebook may have undermined the meaning of the word ‘friend’. Perhaps all that facebook/myspace needs is clearer semantics behind the connections its users form, but it does feel to me at times that the notion of and online ‘friend’ has become garbled… and it seems that limiting the amount of connections you can make might be a start towards making them more useful.
Designing for social networks using these real-world social/cognitive limits might lead to some different interaction arrangements. I had thought of the following:
- For my “select 5″, I would give them the opportunity to directly connect/interrupt me at almost any time. Richer communication channels (video/voice) would be enabled by default.
- For my “trusted 15″, I would grant the opportunity to directly respond on any blog postings/etc without explicit editorial permission. I would publish personal status messages and inside jokes through a limited public interface.
- For my “group of 150″, I would grant permission to see pictures of me and my other friends (I think face recognition technolgy would be great to automatically tag and filter photos so that I wouldn’t have to). I would publish less personal/professional messages that they would be able to see.
- For any individuals above that number, they would be able to see non-personally-identifiable pictures, blog posts, and professional messages.
In general, I think as social networks mature…’less’ will be/mean more.
Filed Under Uncategorized
2 Comments
The Dissertation Marathon
Posted on April 6, 2009
I’m getting close (hopefully) to submitting my dissertation proposal (on music corpus visualization, natch). This has been something that’s been a goal of mine for a long time, and I feel like my enthusiasm alone has carried me up to this point. So, maybe I feel lucky that only recently have I started to feel very run down and disenchanted with the process of writing/editing/reviewing for 4-6 hours everyday.
Anyways, I’ve started doing some things that I think help greatly, and since many of my friends/colleagues are also going through this same process, and mentioned the same problems, I thought I could share some of what I’ve started doing that seems to help. I’ll give them here in order of importance:
- Mood: It’s really easy to get into weird mood swings, particularly if you’re like me, and are no longer on campus, and don’t have a bunch of others around to keep you in check. If you have serious emotional problems, then this advice is not for you. However, I think most people will go through some sort of strange mood while writing, it’s just part of the process. What has helped me a lot in this area has been a simple amino acid called L-Methionine. This is a biochemical precursor to Sam-e, a more expensive natural hormone related to joint strength and mood control. I take L-Methionine, and have noticed a marked improvement in mood with no adverse side effects. I realize of course that all of this is unproven according to the FDA, and some people consider it useless. However, it is perfectly safe. YMMV.
- Sleep: I’ve always had problems sleeping, and it gets worse when I travel. Some of my collegaues suggested Melatonin, which they use to get over jet lag. I have to give it my endorsement as well. I’ve tried prescription strength sleep aids, but this is far better. No side-effects, non-habit forming, and it doesn’t even make me dangerously drowsy. I just feel ready to go to sleep, and sleep better than I do without it.
- Exercise: It’s remarkable to me how exercise can change my mental state. It only takes about 30 min. of jogging, etc. before I have a new perspective on things. It’s also my “canary in the coal mine” for my weekly routine. If I’m not having a good workout, it usually means I’m not getting enough sleep, or not eating right, etc. Then it’s time for a change.
- Diet: Some people are able to control all of these factors with diet and exercise. More power to them. I like more of a variety, so I tend to eat whatever I want (within reason). I’ve got nothing really profound here: the wrong kinds of food can throw everything off kilter, so it’s good to be aware of how they affect you. Generally, I eat first, and ask questions later. It doesn’t get me into too much trouble.
Anyways, these are just tips that seem to work for me, and aren’t supposed to be a guideline. I also don’t consider myself one of the “all-natural” crowd, nor do I endorse any sort of chemical stimulant/barbituate (everything I’ve referenced here has weaker side effects than caffeine/tylenol pm). Writing the dissertation is shaping up to be a long, drawn out affair, and I’m very aware of the percentage of people who end up being A.B.D, which may be as high as 50% in some areas. I just am going to use every tool I have available, and wanted to share them as well.
Filed Under Uncategorized
Leave a Comment
Tutorial: Music Visualization for Discovery
Posted on March 30, 2009
Paul Lamere and I recently got our tutorial accepted to ISMIR 2009. It is titled Using Music Visualizations for Discovery and will be a survey of all the different ways that researchers have approached visualizing music collections, and how we can use these methods to find new and interesting music.
At first glance, this perhaps appears to be a bit of a ‘fringe’ topic. Visualizations are often seen as more of an art form than a straightforward research tool. However, I believe that music is a special form of information. On one hand it behaves according to a set of physical rules, following certain spectral behaviors as an acoustic signal. On the other hand, it behaves as a cultural icon, following another set of rules in a network of contextual associations and systems of meaning. On yet another hand, it is understood in a musicological system of compositional symbols and structures. To study and understand only one aspect of music is to have an incomplete grasp of the role it plays in the other systems. You could spend an incredible amount of time understanding how musical information is related in each context. Perhaps this is why music information retrieval projects spanning different music metadata types are somewhat rare.
Paul and I are believers that visualizations can be effective “big picture” overviews of music corpus information in many different contexts, and can be a great first step towards understanding how each form of music metadata reflects an important way of understanding music. We hope to use our combined expertise to produce a useful overview of the current state of the art in music corpus visualization, as well as provide some useful open source tools for researchers to investigate their own musical information visually.
We’ve been gathering a lot of existing relevant projects already, and have tagged them all on del.icio.us. There’s a lot of great projects on there, and it’s worth a look. If you think we’ve missed something, tag the respective website with “MusicVizIsmir2009″ and we’ll check it out and add it to our collection.
Paul has some information available on his blog…. but just don’t believe everything he says about me, I’m the understudy in this group :)
Filed Under Mapping, Music
Leave a Comment
Misconceptions of dividend producing stock
Posted on March 2, 2009
(Self Disclosure: My father is an investment manager whose portfolios and strategies include dividend producing companies.)
This is way off topic for me, but I’ve been really bothered by all of the anti-wealth sentiment that seems to be growing in the US… that somehow people with a lot of money are the cause of the economic collapse, or that they are hurting the economy by continuing to take their pre-collapse salaries. This sentiment is routinely expressed (of course) towards the CEO’s of big firms, but also now for college basketball coaches.
Apparently, limiting the salaries of corporate/organization heads is not enough, and so right now there is growing sentiment that dividends should be taxed higher, since many heads of companies invest in these stocks to generate income, and by doing so avoid higher tax rates on salaries.
The article goes on to assert that the investment in dividend producing stocks led to greater speculation, which in turn led to the current market state.
One example of “speculative dividend investment gone awry” are the Madoff funds, where individuals and companies bought into his Ponzi scheme, and ended up paying taxes for dividends they never received. However, this had nothing to do with the real culprit of the crash, the mortgage-backed security. The folks that invested with Madoff were duped and robbed. They have nobody to blame but themselves for getting hoodwinked by one of the oldest investment cons in the book. It doesn’t mean the underlying dividend system is flawed, and it doesn’t mean the dividend system contributed to the current market situation.
The reason why dividend income is taxed lower is that it has already been taxed. The companies that offer dividends have already paid taxes on their earnings. Companies (not funds) that offer dividends typically are older, more stable companies that have limited opportunity for growth. By offering dividends, they offer an incentive for investment over another faster growing, but less established company.
The Christian Science Monitor article is wrong on several points. Investing in dividend producing companies is almost always less speculative than non-dividend producing companies. You are typically investing in companies that are producing positive cash flow, and in companies that have been around for a while. This is far safer than investing in other types of companies/funds. This method of investment is also not the sole domain of the super-rich. Anyone can do it, and it remains a powerful tool for people looking to make safer investments in the market.
The government has meddled with investment strategies at its own peril. They encouraged us to buy homes we couldn’t afford, and directly brought about arrangements for loan agencies to buy and sell bad debt. The last thing they should be doing now is discouraging us from investing in strong, stable companies.
It is my belief that we are going to get out of this bad market through “back to basics” economic policies and investment strategies, not by eating the rich.
Filed Under Uncategorized
Leave a Comment
Iterable <Iterable<T>> in haXe
Posted on February 6, 2009
One of the (few) limitations of haXe is that it does not type collections recursively. So, writing a function header of :
public function (it:Iterable<Iterable<T>>) : …{}
will not work in the intended way. In fact, trying to pass a List<List<T>> or [[1,2,3],[4,5,6]] for “it” will cause errors.
This is a limitation for functional programming routines, especially functions that handle collections of collections like chain(), zip(), etc.
In order to handle these situations, it’s necessary to come up with a work-around. For relevant methods, I have a function header that looks like:
function(it:Iterable<Dynamic> , ?nonIterableBehavior<Dynamic>->Iterator<Dynamic>):…
The “it” parameter is a simple single collection of any Type (Dynamic). This will accept Iterable<Iterable<T>>, but also Iterable<T>, or a mixed Iterable of both iterable/non-iterable elements. I’m mainly interested in the first case, but I’ll have to handle the latter two cases as well.
In order to handle the all of the cases, it’s necessary to detect if an individual element T is actually an Iterable<T2> (T2 equals some other type). The straightforward method would be to use Reflect.hasField(”field”, iterator). However, this will not detect the iterator() in Arrays. Also, since we’re using a Dynamic type, we’ll have to test for null. In the end, this should work for an Iterable tester:
public static function isIterable(d:Dynamic):Bool{
return (d != null && (Reflect.hasField(d,’iterator’) || Std.is(d, Array)));
}
As long as the object has an “iterator” field function that behaves in a consistent way, this will work for it.
Now that we can test for Iterables, we can handle non-iterables. In relevant functions I use a function called nonIterableBehavior that transforms these non-iterables into Iterators, and then pass that resulting iterator along to chain as if it were a proper Iterator. In my own classes, nonIterableBehavior defaults to something I thought would be appropriate. For instance, in chain(), the default nonIterable function applies IterTools.repeat(”x”,1) to the non-iterable element. In zip(), the default nonIterable function instead skips any nonIterable elements (skipping is assumed by a function that returns null).
So… the net effect is that I can now call something like
ListTools.chain([[1,2,3,4],5,[6,7,8]])
and get back a List<Dynamic>:
{1,2,3,4,5,6,7,8}
From here, if I need to do anything further with the elements in the list, I’ll have to type check everything with Reflect/Std.is methods like Std.is(x,Float), etc. However, in most of my cases, just printing out a list is useful.
Filed Under Manipulation, haXe
Leave a Comment





















