On 2012/8/15 SteveD <
steve.j...@gmail.com> wrote:
> Here's another way of approaching the same thing. It would be convenient if
> Go used type inference more freely. Say I am passing a function that
> operates on floats and returns floats, then one could say:
>
> MyFunc(func(x) { return x*x })
>
> where the compiler knows perfectly well that MyFunc expects func(float64)
> float64 and can insert this information.
I think it would go a bit too far compared to the usual Go rules. One
thing I would to be able to do in a future version of the language is:
type WalkFunc func(path string, info.os.FileInfo, err error) error
...
F := WalkFunc(path, info, err) {
// do things
return nil
}
just like we can use named types in struct/map/slice literals. Such a
syntax addition would not modify the typing rules.
> So we could get by the same analysis:
>
> F := func(x) { return somefunc("a str",x); }
This is not the same analysis, since in the previous example, the
function type was inferred from the context. Here you have to choose a
default type, like when writing "x := 1" the language says "x will
have type int".
Suppose I write
mustRead := func(r, s) {
n, err := r.Read(s)
if err != nil { panic(err) }
return n
}
what is its type ? is it func(io.Reader, []byte) int ? is it
func(*bufio.Reader, []byte) int ? what about
func(n) { fmt.Println(n) }
In functional programming languages like Haskell, types or similar
expressions can be inferred from how are they are used later, the
compiler is totally different. Haskell is also different in that
variables may be polymorphic functions:
let f x y = x ++ y in show (f [1] [1]) ++ show (f "hello" "world")
where f is used to concatenate both lists of integers and strings.
In Go where each variable must have only one type, it is difficult to
choose what type to give, and also difficult to write the rules for
that choice.
Rémy.