且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获得一个函数来返回不同的类型

更新时间:2023-11-23 21:37:04

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

相关阅读

推荐文章