开发者

How to get a function to return different types

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 usin开发者_运维知识库g it right :P. any help?


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


Functions in Haskell can only return one type so Either will work for you since it would have your function return the type Either (a,b) [(a.b)].

I am not sure what went wrong with how you are using Either but here is a simple example of its usage:

test a b = 
    if a == True 
    then Left (a,b) 
    else Right [(a,b)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜