So, I have a function with multiple definitions (guards), and depending on which one it matches, I'm trying to have it either return an (a,b) or [(a,b)], however the compiler is throwing up errors 'cause they're different types. I was trying to use Either to solve this, but probably not using it right :P. any help?
To allow a function to return multiple data types, you simply add a pipe after a data type.
A function can not return multiple values, but similar results can be obtained by returning an array.
As per the Java Language Specification, the methods in Java can return only one value at a time. So returning multiple values from a method is theoretically not possible in Java.
In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.
Either
-- or a custom data type equivalent to it -- is the only way to do this. Here's a dumb example:
stuff :: Int -> Either (Int,Int) [(Int,Int)]
stuff 0 = Left (0, 0)
stuff n = Right [ (x,x) | x <- [0..n] ]
Then when somebody calls this function, they can pattern match to find out which of the two types it returned:
foo n = case stuff n of
Left (a,b) -> ...
Right pairs -> ...
However, knowing nothing about your problem, in general I would recommend thinking a bit more about the meaning of your function. What does it take, what does it return? Be precise, mathematical. The simpler the answer, the more smoothly this function will work with the rest of your program and the concepts of Haskell. For me, in such descriptions, Either
rarely turns up. How can you unify the two results? Maybe you just return the singleton list [(a,b)]
instead of Left (a,b)
, if that makes sense for your function.
Haskell does not play well with functions that try to be too smart, the type that you may be used to from Python or jQuery. Keep it dumb and precise -- get your complexity from composing these simple pieces. If you are curious about this, ask another question with more details about your problem, what you are trying to accomplish, and why you want it to work that way. Sorry for the preaching :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With