如何获得一个函数来返回不同的类型 [英] How to get a function to return different types

查看:134
本文介绍了如何获得一个函数来返回不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个具有多个定义(守卫)的函数,并且根据哪一个匹配,我试图让它返回一个(a,b)或[(a,b)],但是编译器正在抛出错误,因为它们是不同的类型。我试图用Either解决这个问题,但可能没有正确使用它:P。任何帮助?

解决方案 - 或者自定义数据类型等效它是唯一的方法来做到这一点。这是一个愚蠢的例子:

  stuff :: Int  - > (Int,Int)[(Int,Int)] 
stuff 0 = Left(0,0)
stuff n = Right [(x,x)| x < - [0..n]]

然后当有人调用这个函数时,匹配找出它返回的两种类型:

  foo n = 
的案例n左(a ,b)→> ...
右对 - > ...

然而,对于你的问题一无所知,总的来说,我会建议多思考一下你的函数的含义。它需要什么,它会返回什么?精确,数学。答案越简单,这个函数就会越顺利地与你的程序的其余部分和Haskell的概念一起工作。对于我来说,在这样的描述中,或者很少出现。你如何统一这两个结果?也许你只是返回单独列表 [(a,b)] 而不是 Left(a,b),if这对你的函数是有意义的。



Haskell不太适合那些试图太聪明的函数,这种类型可以从Python或jQuery中使用。保持愚蠢和精确 - 从这些简单的作品中复制这些简单的作品。如果您对此感到好奇,请提出另一个问题,提供有关您的问题的更多详细信息,您要完成的内容以及为什么要以此方式工作。对不起,传道: - )


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?

解决方案

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

这篇关于如何获得一个函数来返回不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆