in reply to Currying--useful examples?

Here's the example I usually give in talks etc.. Say you have an HTML editor that has bold, underline and italics. Instead of writing three functions, have the compiler write them for you:

sub mk_tagger { my($tag) = @_; return sub { my($txt) = @_; "<$tag>$txt</$tag>" }; } my ($bold, $underline, $italic) = map { mk_tagger($_) } qw( b u i ); print $bold->("what a " . $underline->("nice") . $italic->(" day"));

Here's the equivalent Perl 6:

sub mk_tagger ($tag) { -> { "<$tag>$^txt</$tag>" } }

The idea is that the mk_taggger function is intentionally designed not to be used directly but to generate tagging functions.

Update: In Haskell and other languages that had autocurrying, you'd not need this explicit distinction.

tagStr :: String -> String -> String tagStr tag text = "<" ++ tag ++ ">" ++ text ++ "</" ++ tag ++ ">" -- now I can use it either way. tagStr "b" "a bold moose" underline = tagStr "u" underline "an underlined moose"

Replies are listed 'Best First'.
Re^2: Currying--useful examples?
by gaal (Parson) on Jan 10, 2007 at 20:50 UTC
    Of course, to say "<" ++ tag ++ ">" is very ugly, so you'd want to write it as angle tag. angle is a function? How is it implemented? In typical function programming style:

    angle :: String -> String angle s = surround "<" ">" s {- This can, in "points free" style, be written: angle = surround "<" ">" -- look ma, no explicit variable! -} surround :: String -> String -> String -> String surround start end text = start ++ text ++ end -- The idea is to reuse surround: quote = surround "'" "'" bracket = surround "[" "]" braces = surround "{" "}" ... etc.
    But this is straying off-topic for this site...