Hacker News new | ask | show | jobs
by gutsy 4665 days ago
MULTIPLE return values?! My mind is BLOWN. That's awesome. My work is all in Java and there are so many times on my last project where that would have been helpful (I know I can do it by creating a map or an array or something, but that's stupid and extra code that I shouldn't need to write).

I really hope to be able to write Go professionally at some point, it is a really nice language to write in.

4 comments

Any language with tuples automatically gets "anonymous" multiple return values. (e.g. Python's `(1, "foo", None)`.)

(Go's multiple return values seem to just be simulating a single use case of proper tuples.)

Well, all I've written since college has been Java, so this is all new to me. I've only briefly checked out Ruby and Python, and not enough to really know that much about either language.
If that blows your mind, check out Haskell - you can dispatch on type of return value.
This is the first one-liner I've read that actually explains something useful I can do with higher-order type inference. Preventing errors at compile time doesn't count; doing something is run-time by definition.

Thanks.

Interesting, hadn't even considering looking at Haskell at all.
Care to elaborate?
As an easy to follow (though questionably idiomatic) example, consider the typeclass Default:

    class Default a where
        def :: a
and an unwise pair of instances:

    instance Default Int where
        def = 7

    instance Default String where
        def = "foo"
This means I can say:

    3 + def + length ("c" ++ def)
and get back 14. Note that which "def" depends on the type expected where it is used.

---

It's not limited to values, either. Consider the "return" function in the Monad typeclass:

    return :: Monad m => a -> m a
which is a function that takes something and returns that something wrapped in a monad. Which monad? Whatever is expected at the call site.

    [1, 2, 3] ++ return 4
gives us [1, 2, 3, 4] because list is a monad and return for lists gives a single element list, whereas

    putStrLn "foo" >> return 4
gives us an IO action that, when executed, prints "foo" and yeilds a 4.

---

A super complex example is variadic functions like printf, with the type

    printf :: PrintfType r => String -> r
PrintfType can be a String or IO (), giving you something like C's sprintf or printf based on the call site (which is itself cool), but it can also be a function that takes an instance of PrintfArg and gives back some new PrintfType (in an interesting intersection with currying).
You can do multiple return values of mixed (and non-predetermined) types in Ruby too.
Meh, not really. In ruby `return x, y` is just syntactic sugar for `return [x, y]`, ie returning an array. It's also an indication that you probably need a class.
I did not know that, but then I've only played around with Ruby a little bit.
multiple-value-bind. Old as Lisp