I've found out that you can actually get something like partial
application, although it's slightly kludgy. I have searched the list
for a discussion of the problem, so I'd like to post a short
demonstration.
Say you have a function func cat(l, r string) string. It concatenates
two strings. For some reason, you want to bind the left parameter to
"foo" and pass around a function that joins various strings to "foo."
In languages like python you might pull out
f = functools.partial(cat, "foo")
As far as I know there is no such library in Go. However, you can hack
it by allocating anonymous functions:
package main
import (
"fmt"
)
func cat(l, r string) string {
return l + r
}
// Note: this does not have to be in a separate
// function. I only allocate the partially applied
// function here to demonstrate that it works
// even when the bound variable does not
// appear in the scope of the caller.
func getCatToFooFunc() func (string) string {
return func (r string) string {
return cat("foo", r)
}
}
func main() {
catToFoo := getCatToFooFunc()
fmt.Printf("%s\n", catToFoo("bar"))
fmt.Printf("%s\n", catToFoo("barbaz"))
fmt.Printf("%s\n", catToFoo("mofuu"))
}
If anyone can figure out how to generalize this into a function called
"partial" or something like that, I'd be appreciative, but it doesn't
seem like it is possible without being able to do something like
python's *args operator.
I think the main limiter is the lack of named parameters in Go.
Without named parameters, one is limited by the parameter order. The
example provided in Python's documentation specifies the 'base'
parameter, which is the second parameter in the function 'int'. I
managed to get around this, in my attempt to create implement Partial,
by using a struct whose fields correspond to the function's
parameters. This allows me to emulate named parameters by specifying
keys in a composite literal. It's 101 lines of code, so here it is in
a pastie:
-Daniel
2010/3/13 Ostsol <ost...@gmail.com>:
-1 to named parameters, they make people think functions with dozens
of 'optional' arguments are somehow OK, they are one of the reasons
most python APIs are such a mess.
> +1 to partial function application ala (python|haskell?)
If function arguments remain simple and concise, there is less need for this.
uriel
In fairness this is more a problem with default params than named
params. I can see some benefit to named params, in the same vein as
specifying fields in struct constructors. But in general I agree,
keeping function definitions and function calls simple is a laudable
goal.
On Sun, Mar 14, 2010 at 1:15 AM, Alejandro Castillo <pya...@gmail.com> wrote:-1 to named parameters, they make people think functions with dozens
> +1 to named parameters ala python
of 'optional' arguments are somehow OK, they are one of the reasons
most python APIs are such a mess.
If function arguments remain simple and concise, there is less need for this.
> +1 to partial function application ala (python|haskell?)