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 Functions
Higher 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):
Prelude> :t map
map :: (a -> b) -> [a] -> [b]
Prelude>
Example of usage could be like this:
Prelude> map even [1..10]
[False,True,False,True,False,True,False,True,False,True]
Prelude>

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:
[altair@stormwind diveintoperl6]$ cat > higher-order.p6
#!/usr/bin/env pugs
use v6;

sub hiordr(&b,$v) {
b $v;
}

hiordr({ say $_; },"asdf");
[altair@stormwind diveintoperl6]$ pugs higher-order.p6
asdf
[altair@stormwind diveintoperl6]$
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:

[altair@stormwind diveintoperl6]$ cat map-filter.p6
#!/usr/bin/env pugs
use v6;

sub map2(&b,@l) {
my @r = <>;
for @l -> $v {
@r.push(b $v);
}
return @r;
}

sub filter2(&p,@l) {
my @r = <>;
for @l -> $v {
my $x = p $v;
@r.push($v) if $x;
}
return @r;
}

say map2({ .uc; },<a b c d>).join(' ');
say filter2({ $_ % 2 == 0; },1..10).join(' ');
[altair@stormwind diveintoperl6]$ pugs map-filter.p6
A B C D
2 4 6 8 10
[altair@stormwind diveintoperl6]$

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 matching
In 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:

haskell:
rev [] = []
rev (x:xs) = rev xs ++ [x]

perl 6:
multi sub rev () { () }
multi sub rev($x,*@xs) { (rev(|@xs),$x) }


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: Monads
A 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:

data Click a = Clicked a | Silence
deriving Show

instance Monad Click where
return = Clicked
Silence >>= _ = Silence
Clicked a >>= f = f a
Easy enough. Here's a function and a few tests to show how exactly this monad works:

noise :: (Num a) => a -> Click a
noise 0 = Silence
noise x = Clicked x

t1 = do
a <- noise 10
b <- noise 5
return (a + b)

t2 = do
a <- noise 10
b <- noise 0
return (a + b)

t3 = do
a <- noise 10
b <- noise 0
c <- noise 5
return (a + c)
Running these:
[altair@stormwind monads]$ ghci

Prelude> :l Click.hs
[1 of 1] Compiling Click ( Click.hs, interpreted )
Ok, modules loaded: Click.
*Click> t1
Clicked 15
*Click> t2
Silence
*Click> t3
Silence
*Click>


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 <- noise 0 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:


my $t1 = monaddo ({ my $a = noise 10; },
{ my $b = noise 5; },
{ return $a + $b; });



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:
pugs> sub monaddo(&b,*@a) {
....> my $x = b();
....> $x = $_($x) for @a;
....> }
pugs>

And an example of the usage:
pugs> monaddo({ 1; },{ .say; });
1
pugs>

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) Conclusion
This 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?

49 comments:

Unknown said...

Oooh, pretty do blocks :)

We can use macros to take some more natural syntax and translate it to whatever syntax is required to get the mechanics right.

Rather than iterating a list of closures, why not translate it into a series of nested closures?

Next thing to do is to make sure that the inferred type of each closure correctly chains or matches the type of the monad.

I think it's definitely worth taking a closer look at. :)

Anonymous said...

viagra faq buy generic viagra is there a female viagra viagra samples viagra by mail viagra rrp australia cost side effects of viagra viagra from india cheap viagra overnight buy viagra online at does watermelon have viagra effect viagra paypal natural herbs used as viagra how does viagra work

Anonymous said...

[url=http://sunkomutors.net/][img]http://sunkomutors.net/img-add/euro2.jpg[/img][/url]
[b]cheap downloadable oem software, [url=http://sunkomutors.net/]buy wholesale software[/url]
[url=http://sunkomutors.net/][/url] purchase used software Deluxe 2009 Mac Parallels
game software for sale [url=http://sunkomutors.net/]icon plugin for acdsee[/url] have to buy photoshop
[url=http://sunkomutors.net/]filemaker pro password recovery[/url] software purchase australia
[url=http://sunkomutors.net/]software at discounted[/url] discount software ms
where to buy adobe software [url=http://sunkomutors.net/]buy windows software online[/b]

Anonymous said...

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 need
AimTrust 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

Anonymous said...

[url=http://hopresovees.net/][img]http://bariossetos.net/img-add/euro2.jpg[/img][/url]
[b]buy photoshop on, [url=http://vonmertoes.net/]autodesk autocad[/url]
[url=http://bariossetos.net/][/url] adobe picture editing software buy cheap software online
cheap language software [url=http://bariossetos.net/]e commerce store software[/url] microsoft presentation software
[url=http://hopresovees.net/]quarkxpress 6.52 crashes in windows vista save[/url] latest adobe photoshop software
[url=http://bariossetos.net/]express software price[/url] downloading softwares
buy dreamwaver [url=http://vonmertoes.net/]educational discount on software[/b]

Anonymous said...

[url=http://murudobaros.net/][img]http://murudobaros.net/img-add/euro2.jpg[/img][/url]
[b]and software shops, [url=http://murudobaros.net/]adobe web premium cs3 photoshop building twain menu items[/url]
[url=http://murudobaros.net/]7 Mac[/url] where to buy macromedia how to sale software
to buy old software [url=http://murudobaros.net/]buy microsoft office software[/url] cheap ms software
[url=http://murudobaros.net/]software developers in canada[/url] software purchases
[url=http://murudobaros.net/]tools software purchase[/url] education discount on software
adobe web software [url=http://murudobaros.net/]shop softwares[/b]

Anonymous said...

[url=http://hopresovees.net/][img]http://hopresovees.net/img-add/euro2.jpg[/img][/url]
[b]adobe photoshop cs4 tutorials, [url=http://hopresovees.net/]software corporation canada[/url]
[url=http://bariossetos.net/][/url] software microsoft word coreldraw 12 trial
software shop of [url=http://bariossetos.net/]to sell software in[/url] academic library software
[url=http://bariossetos.net/]adobe photoshop cs3 activation software[/url] where to buy used software
[url=http://hopresovees.net/]corel draw graphics suite x4 coreldraw manual[/url] student discount software
microsoft smartphone software [url=http://bariossetos.net/]windows vista oem software[/b]

Anonymous said...

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]

Anonymous said...

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.

[url=http://theinvestblog.com] Online investment blog[/url]

Anonymous said...

attackers samples mensingwerum descendants bbusiness participates inspiring datathe subcategory catholic geek
servimundos melifermuly

Anonymous said...

statistics snatch vineyards clerical asap firewalls paranoia fangled accessible improperly identifier
servimundos melifermuly

Anonymous said...

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]

Anonymous said...

Good fill someone in on and this fill someone in on helped me alot in my college assignement. Thanks you for your information.

Anonymous said...

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.


(Posted on Nintendo DS running [url=http://kwstar88.livejournal.com/491.html]R4[/url] DS SerVo)

Anonymous said...

[url=http://sopriventontes.net/][img]http://sopriventontes.net/img-add/euro2.jpg[/img][/url]
[b]buy adobe photoshop uk, [url=http://tonoviergates.net/]adobe acrobat 9 pro oem[/url]
[url=http://sopriventontes.net/]9 Pro Extended[/url] a niche store software 10 Advanced Mac Retail
Standart Edition Mac Retail [url=http://tonoviergates.net/]where can i buy photoshop[/url] QuarkXPress 8 Mac
[url=http://tonoviergates.net/]to buy adobe software in[/url] quarkxpress tutorials
[url=http://tonoviergates.net/]customer order software[/url] cheap pdf software
store checkout software [url=http://tonoviergates.net/]macromedia fireworks software[/url][/b]

Anonymous said...

Brim over I agree but I contemplate the post should acquire more info then it has.

Anonymous said...

[url=http://www.ile-maurice.com/forum/members/wetter-vorhersage.html][b]wetter 2[/b][/url]

[url=http://www.ile-maurice.com/forum/members/wetter-vorhersage.html][b]deutscher wetter dienst[b][/url]

Anonymous said...

Predilection casinos? probe this advanced [url=http://www.realcazinoz.com]casino[/url] advisor and aside online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also into our latest [url=http://freecasinogames2010.webs.com]casino[/url] orientate at http://freecasinogames2010.webs.com and bring pang in equitably fabulously away !
another late-model [url=http://www.ttittancasino.com]casino spiele[/url] attentiveness is www.ttittancasino.com , pro german gamblers, inadvertence in freed online casino bonus.

Anonymous said...

http://diversitae.blogspot.com/2009/08/el-foro-en-independencetoday.html

Anonymous said...

www.weather.com

Anonymous said...

http://www.facebook.com/pages/weathercom/298713874092
www.weather.com

Anonymous said...

Nice post and this enter helped me alot in my college assignement. Thanks you for your information.

Anonymous said...

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].

Anonymous said...

ixNuDp synthroid discount eNHvAG tadacip 10mg XKmSNt tadalis sx free pills NcMnlE tamiflu rx xCxXEW tegretol 50mg QbNlai tenormin free pills teIMfZ tentex forte online

Anonymous said...

Glad to greet you, ladies and gentlemen!

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.

Anonymous said...

pjY3mcNtu Mountaineer Casino jtCq8xT2D Casino Server qNnYurh8R Ace Casino 1jk2lVmzK Maxima Casino yZ9f0U8xD Casino City FauMHfwAxW Video Casino QRbY5hTLs0 Slots Casino ZIBmH6bPXD Casino Card Game

Anonymous said...

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.

Anonymous said...

Good day

We do not agree with this year BRITs 2010 decision.

Please go to see our little web poll

http://micropoll.com/t/KDqOnZBCWt

Lady Gaga can not be better than Nina Hagen

Poll supported by BRIT awards 2010 sponsor femmestyle
[url=http://www.femmestyle.ch/schoenheitschirurgie/facelift/index.html]facelift[/url]

PRINCE HARRY WISHES HAPPY BIRTHDAY TO THE BRIT AWARDS
With a special birthday message from Prince Harry for the 30th Anniversary of the BRIT Awards

Anonymous said...

Splendidly done is well-advised b wealthier than extravagantly said.

Anonymous said...

Well done is richer reconsider than extravagantly said.

Anonymous said...

Lovingly done is richer reconsider than comfortably said.

Anonymous said...

A human beings who dares to decay one hour of one of these days has not discovered the value of life.

[url=http://www.gripesonline.com/forum/members/ronaoore.html]Mark[/url]


Jake

Anonymous said...

A human beings who dares to waste one hour of age has not discovered the value of life.

[url=http://www.btween.co.uk/users/allenpaul]Ana[/url]


Linda

Anonymous said...

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.

stapler

[url=http://stapler-78.webs.com/apps/blog/]stapler[/url]

Anonymous said...

A humankind begins icy his wisdom teeth the earliest chance he bites out more than he can chew.

Anonymous said...

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.

Anonymous said...

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.

Anonymous said...

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.

Anonymous said...

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.

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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

Anonymous said...

[url=http://newloans.skachatnow.co.cc/direct-education-government-loan.php]direct education government loan[/url]
http://loanstoday.skachatnow.co.cc/auto-bad-credit-loan-wisconsin.php - auto bad credit loan wisconsin
[url=http://loanstoday.skachatnow.co.cc/personal-loan-fixed.php]personal loan fixed[/url]
http://newloans.skachatnow.co.cc/bad-credit-car-loan-ford.php - bad credit car loan ford
[url=http://fastloans.skachatnow.co.cc/fax-less-payday-loan.php]fax less payday loan[/url]
http://newloans.skachatnow.co.cc/canada-college-detailed-loan-student.php - canada college detailed loan student
http://newloans.skachatnow.co.cc/application-loan-online-personal.php - application loan online personal
[url=http://getloan.skachatnow.co.cc/calculator-consolidation-loan-student.php]calculator consolidation loan student[/url]
[url=http://newloans.skachatnow.co.cc/100-construction-loan.php]100 construction loan[/url]
http://loanstoday.skachatnow.co.cc/online-auto-loan-company.php - online auto loan company

Anonymous said...

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

Anonymous said...

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.

[url=http://petitelectromenager.eu]Fours micro-ondes[/url]
Couteaux electriques

Anonymous said...

Genial brief and this enter helped me alot in my college assignement. Say thank you you for your information.

Anonymous said...

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.

Anonymous said...

I'm Glad i came across this web site.Added diveintoperl6.blogspot.com to my bookmark!

lesbian dildo bondage said...

I was interested know about it.