Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a function to return different types

Tags:

haskell

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?

like image 575
Chris Bolton Avatar asked Jan 22 '11 22:01

Chris Bolton


People also ask

How do you make a function return different types?

To allow a function to return multiple data types, you simply add a pipe after a data type.

Can a function return different data types?

A function can not return multiple values, but similar results can be obtained by returning an array.

Can a method return multiple types?

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.

Can a python function return different types?

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.


1 Answers

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 :-)

like image 71
luqui Avatar answered Nov 08 '22 04:11

luqui