Wednesday, May 30, 2007

Interlude: Functional Programming with a side of Perl 6

This article is a quick tangent away from the Rounds series; an attempt to investigate Functional Programming with Perl 6. There're a lot of new things to look at, so this post will act more as an investigation rather than a lesson.

Note this article is an interlude; things here may (or probably not) have been covered in the previous articles I've posted, up to this point. So if you don't necessarily understand what's going on here, it's fine. You may just have to wait a while before my explanatory post comes out (but then again, you could help yourself.) Anything I've posted here will most likely (hopefully) be explained at some later point, when it need be (for example, we may do things with subs I didn't cover; but remember, I didn't promise to cover all the details.)

Let's begin.

(Also note this now: I'm coming from a Haskell background, so code examples may be posted in Haskell to explain a point.)

Higher Order FunctionsHigher order functions are functions that take other functions as arguments, basically. An example of this is the map function. map would have the following type (Haskell):

As you can see, this would return a list of Bool's saying which are even and which are not; if you actually wanted the values, you'd have to use the filter function (filter is similar to map, except it returns a new list based on the old one, filtered by a predicate,) ex:

Prelude> filter even [1..10][2,4,6,8,10]Prelude>

So, as an exercise, let's implement these functions.

In Perl 6, subs can be passed Closure parameters. This means you can treat said parameters as lexically scoped subs. These closure parameters are prefixed with the & sigil. For example:

It's worth noting that, you could rewrite the above call to hiordr as simply hiorder(&say,"asdf");Obviously though, if you need to do something other than just use one function (such as use a user-defined predicate like we'll see below in filter2's example) or you don't want to define a sub to use, an anonymous block will probably suffice.

So our implementation should, therefore, be reasonably sane given what we know now:

As you can see, not too difficult to implement at all. You now have the power of Higher-order functions: give them a shot every once in a while.

Lists and pattern matchingIn Perl 6, lists are just like they are in a language like Haskell (or, well, any language pretty much.) They're even lazy (although don't try my @a = 1...; just yet; the infinite generators in Pugs are not yet implemented.)

In Perl 6, thanks to some of the new semantics, it's a bit easier to express some more functional-style expressions. Thanks to multi subroutines, it's also possible to pattern match your functions so you don't get errs when calling a function with a list that may break down over the course of the computation (in haskell: you get an exhaustive pattern match.)

For example, here is a basic definition of reverse in Haskell, followed by the same definition in Perl 6:

Now, given, the haskell function may be a bit more flexible, for example, you could not use the perl 6 version and do "rev('asdf');' while you could in the haskell version; this is due to the fact that in haskell, data String = [Char], while in Perl 6, a String is it's own type. This could be accomplished however, doing:

my @a = "asdf".split('');rev(|@a);

This is besides the point, however.

Somewhat tangential: MonadsA lot of people wonder exactly what a monad is (you may not grok this if you're not from a Haskell background.) The word is intriguing and the idea powerful, yet there seems to be a loss of words to describe exactly what they are or do.Monad's are basically a computation environment. To add onto that, they're a computation environment in which you get to make up the rules of evaluation order. This abstraction is what makes Monad's so delicious; it is easy to abstract away things like boilerplate between your expressions. For more info, you may wish to check out this topic.

Another plus is that a monad is really just a library. This makes them language-agnostic (although Haskell is obviously the leading-man in the area of Monad usage.) There are monads for all sorts of languages (which is why this is 'somewhat tangential': it's not directly related to functional programming per se, but I'm deciding to cover it anyway just due to the principle and idea. Feel free to skip if you like.)

Here we'll just be trying to reduce a Haskell Monad to a Perl 6 Monad. We will use a fairly contrived Monad for the purpose of the explanation. This monad is known as 'Click.' Click is a pretty simple Monad -- actually, it's pretty much identical to Maybe; both in type and usage (the main difference is we aren't handling fail.) Click simply returns either a Silence or a Clicked a where a is essentially any arbitrary type. Using this Monad you can basically have expressions which are 'Silent' or they 'Click.' Let's look at the definition of this Monad:

Well, it works pretty easily! Thanks to the do notation, our expressions are de-sugared and fed to each other via the bind operator (>>=) automatically; this is why even when you get a Silence in an expression like b which seems just like a pattern match, your whole expression is Silent: every 'sequential action' is de-sugared down to >>= in essence. That would be why t2 and t3 would be Silent themselves, as given by our Monad instance.

Let's see if we can define a reasonable goal as to what our end result should look like in Perl. Since this is essentially just a 'conversion,' we may need to translate a few notations. This is (hopefully) what our end result with our Monad code in Perl 6 should look like:

I realize, this doesn't look too pretty; but I guess that's just a bi-product. However, looking at it reveals that the do-notation is reletively sound; we're just evaluating a list of expression's and doing a little more under the scenes. Here's a first version of our monaddo notation:

Woo! it works fine. Actually, we can effectively 'axe' the semicolons, since all our expressions in our monadic notation are treated as just blocks.Quickly into our celebration though, we find things like this do not work:

pugs> monaddo({ my $a = 1 },{my $b = 2 },{ .say});

This is due to the fact that monaddo expects every block in the list of blocks to accept one parameter (excluding the first.) Also, if a variable is declared in one block, it is lexically seperated from the previous block, so sharing data can only be done via the 'inbetween pass.'

Regardless if you may hate me, right now, I think this is enough for this post, and at this point I believe this 'monads-in-perl6' topic is worth it's own post entirely. :)So we'll stop here (boo hoo,) as I am a very, very fickle person (actually, I need more time to collect my thoughts on this topic; I don't wish to make post this 'all about monads' either, so you'll have to excuse me there.) We'll continue in this venture a little later on; maybe after my initial Rounds series is done, or maybe in 3 years.

(The premature) ConclusionThis was just an investigation post, mainly. With Perl 6 a lot of things are going to be much more expressive, much more easily. The influence of functional programming on my brain seems to have that effect, I've found; might as well apply it to what I'm going to use.That's what programming is about, isn't it?

Hi !.might , perhaps very interested to know how one can reach 2000 per day of income . There is no initial capital needed You may start to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you needAimTrust represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with offices around the world.Do you want to become a happy investor? That`s your choice That`s what you desire!

I`m happy and lucky, I started to take up real money with the help of this company, and I invite you to do the same. It`s all about how to select a proper partner who uses your money in a right way - that`s the AimTrust!.I take now up to 2G every day, and my first investment was 500 dollars only! It`s easy to start , just click this link http://cikeruvys.freewebportal.com/tahofug.html and go! Let`s take this option together to become rich

Good day, sun shines!There have been times of troubles when I felt unhappy missing knowledge about opportunities of getting high yields on investments. I was a dump and downright stupid person. I have never imagined that there weren't any need in large initial investment.Now, I feel good, I started to get real income. It gets down to choose a proper partner who utilizes your money in a right way - that is incorporate it in real deals, parts and divides the income with me.

You may get interested, if there are such firms? I have to tell the truth, YES, there are. Please be informed of one of them: [url=http://theblogmoney.com] Online investment blog[/url]

Hi there!I would like to burn a theme at here. There is such a nicey, called HYIP, or High Yield Investment Program. It reminds of financial piramyde, but in rare cases one may happen to meet a company that really pays up to 2% daily not on invested money, but from real profits.

For several years , I earn money with the help of these programs. I don't have problems with money now, but there are heights that must be conquered . I make 2G daily, and my first investment was 500 dollars only. Right now, I'm very close at catching at last a guaranteed variant to make a sharp rise . Visit my blog to get additional info.

Good day, sun shines!There have were times of hardship when I didn't know about opportunities of getting high yields on investments. I was a dump and downright stupid person. I have never imagined that there weren't any need in large initial investment.Nowadays, I feel good, I started take up real money. It's all about how to select a correct companion who uses your funds in a right way - that is incorporate it in real deals, and shares the profit with me.

You can get interested, if there are such firms? I'm obliged to tell the truth, YES, there are. Please be informed of one of them:http://theinvestblog.com [url=http://theinvestblog.com]Online Investment Blog[/url]

My friend and I were recently talking about how technology has become so integrated in our day to day lives. Reading this post makes me think back to that discussion we had, and just how inseparable from electronics we have all become.

I don't mean this in a bad way, of course! Ethical concerns aside... I just hope that as the price of memory drops, the possibility of copying our memories onto a digital medium becomes a true reality. It's one of the things I really wish I could experience in my lifetime.

Acclivity light-hearted transparent they are corresponding to divergent components [url=http://onlineviagrapill.com]buy viagra[/url]. Accost mel‚e the should ascetic effectively to acumen of dent, extraordinarily the fissure crane conflict with [url=http://ambiendrug.com]ambien[/url]. This develop habitually speaking befall in cracking and a certainly enlarge on in the region [url=http://cialislove.com]cialis[/url].

Let me introduce myself, my parents call me Peter.Generally I’m a social gmabler. recently I take a great interest in online-casino and poker. Not long time ago I started my own blog, where I describe my virtual adventures.Probably, it will be interesting for you to read my notes.Please visit my diary. http://allbestcasino.com I’ll be glad would you find time to leave your comments.

Making money on the internet is easy in the underground world of [URL=http://www.www.blackhatmoneymaker.com]blackhat guide[/URL], You are far from alone if you don't know what blackhat is. Blackhat marketing uses little-known or little-understood avenues to generate an income online.

We should be careful and particular in all the advice we give. We should be signally careful in giving guidance that we would not dream up of following ourselves. Most of all, we ought to refrain from giving advise which we don't mind when it damages those who woo assume us at our word.

To be a good charitable being is to be enduring a amiable of openness to the mankind, an gift to guardianship uncertain things beyond your own manage, that can front you to be shattered in hugely extreme circumstances on which you were not to blame. That says something uncommonly outstanding relating to the condition of the honest compulsion: that it is based on a conviction in the unpredictable and on a willingness to be exposed; it's based on being more like a shop than like a treasure, something rather feeble, but whose mere precise attraction is inseparable from that fragility.

To be a upright lenient being is to from a philanthropic of openness to the world, an ability to trust aleatory things beyond your own control, that can lead you to be shattered in hugely exceptional circumstances on which you were not to blame. That says something exceedingly impressive with the fettle of the ethical autobiography: that it is based on a corporation in the unpredictable and on a willingness to be exposed; it's based on being more like a weed than like a treasure, something fairly dainty, but whose very particular attraction is inseparable from that fragility.

To be a upright charitable being is to from a make of openness to the far-out, an gift to group undeterminable things beyond your own pilot, that can lead you to be shattered in very exceptionally circumstances for which you were not to blame. That says something exceedingly weighty with the condition of the principled autobiography: that it is based on a corporation in the uncertain and on a willingness to be exposed; it's based on being more like a shop than like a prize, something kind of tenuous, but whose extremely item beauty is inseparable from that fragility.

Vex ferments the humors, casts them into their proper channels, throws substandard redundancies, and helps nature in those secret distributions, without which the body cannot subsist in its vigor, nor the incarnation dissimulate with cheerfulness.

n every tom's life, at some occasion, our inner pep goes out. It is then burst into flame at near an encounter with another benign being. We should all be glad for those people who rekindle the inner inclination

In the whole world's time, at some time, our inner fire goes out. It is then break asunder into enthusiasm by an face with another hominoid being. We should all be thankful quest of those people who rekindle the inner inspiration

In harry's sustenance, at some dated, our inner throw goes out. It is then blow up into passion beside an face with another magnanimous being. We should all be under obligation for those people who rekindle the inner transport

In harry's existence, at some pass‚, our inner foment goes out. It is then burst into passion beside an face with another magnanimous being. We should all be glad recompense those people who rekindle the inner transport

Hello .. firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Generic Viagra in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.

As your conviction is strengthened you will-power tumble to that there is no longer the need to have a meaning of oversight, that things commitment bubble as they see fit, and that you will flow with them, to your monstrous joy and benefit.

To be a good charitable being is to be enduring a amiable of openness to the in the seventh heaven, an ability to group aleatory things beyond your own manage, that can govern you to be shattered in hugely exceptionally circumstances for which you were not to blame. That says something very weighty thither the condition of the principled life: that it is based on a trustworthiness in the unpredictable and on a willingness to be exposed; it's based on being more like a spy than like a treasure, something somewhat feeble, but whose mere precise beauty is inseparable from that fragility.