首页 > 解决方案 > Haskell - 如何将 Either 返回到我的自定义类型?

问题描述

我和 GHC 还不是朋友。我希望它了解我的返回类型是我的自定义类型。

具体来说,我想确保编译器实际上返回了 OAuth2Response。有没有一种惯用的方法来实现这一目标?

例子:

data OAuth2Response = Either OAuth2Error OAuth2AccessToken

getAuthorized :: (..) -> (..) -> OAuth2Response
getAuthorized = do
  a <- nonceValidation (Returns Left OAuth2Error or Right "")
  b <- getAccessToken (Returns Left OAuth2Error or Right OAuth2AccessToken
  b

编译器错误信息

• Couldn't match type ‘Either OAuth2Error OAuth2AccessToken’
                 with ‘OAuth2Response’

标签: haskell

解决方案


data OAuth2Response = Either OAuth2Error OAuth2AccessToken

我不认为这个定义和你想的一样。特别是,Either这里不是指Prelude 中定义的Either 类型构造函数,而是指作为此声明的一部分定义的数据构造函数。

我认为你的意思是

type OAuth2Response = Either OAuth2Error OAuth2AccessToken

即为Either您感兴趣的特定类型定义类型同义词。


推荐阅读