6 ms·
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 help
by gutsy 13y 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.
- dllthomas 13y agoIf that blows your mind, check out Haskell - you can dispatch on type of return value.
- samatman 13y agoThis 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.
- th0114nd 13y agoCare to elaborate?
- dllthomas 13y agoAs 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).
- gutsy 13y agoInteresting, hadn't even considering looking at Haskell at all.
- tibbon 13y agoYou can do multiple return values of mixed (and non-predetermined) types in Ruby too.
- dbaupp 13y agoAny 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.)
- gutsy 13y agoWell, 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.
- lelf 13y agomultiple-value-bind. Old as Lisp