制作一个类型类,不能从上下文中推导出来
我使用仆人库,我想自动将结果映射到错误代码。 仆人期望的类型: Either (Int, String) a
。
例如,如果我有一个类型为: IO (Maybe User)
的模型函数。 我想在Nothing上将(404, "Not Found")
和User
如果它存在)
要做到这一点,我正在写一个typeclass!
class Servile a where
toStatus :: ToJSON val => a -> Either (Int, String) val
instance ToJSON a => Servile (Maybe a) where
toStatus Nothing = Left (404, "Not Found")
toStatus (Just a) = Right a
我还有其他我想写的例子,但是这个给了我错误:
Could not deduce (a ~ val)
from the context (ToJSON a)
bound by the instance declaration at Serials/Api.hs:90:10-38
or from (ToJSON val)
bound by the type signature for
toStatus :: ToJSON val => Maybe a -> Either (Int, String) val
at Serials/Api.hs:91:5-12
‘a’ is a rigid type variable bound by
the instance declaration at Serials/Api.hs:90:10
‘val’ is a rigid type variable bound by
the type signature for
toStatus :: ToJSON val => Maybe a -> Either (Int, String) val
at Serials/Api.hs:91:5
Relevant bindings include
a :: a (bound at Serials/Api.hs:92:20)
toStatus :: Maybe a -> Either (Int, String) val
(bound at Serials/Api.hs:91:5)
In the first argument of ‘Right’, namely ‘a’
In the expression: Right a
什么是正确的方法来做到这一点?
另一种解决方案是,如果你想使用一些非参数化类型,则使用TypeFamilies
:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
module Temp where
import Data.Monoid
class ToStatus a where
type Val a
toStatus :: a -> Either (Int, String) (Val a)
instance ToStatus (Maybe a) where
type Val (Maybe a) = a
toStatus Nothing = Left (404, "Not Found")
toStatus (Just v) = Right v
instance Show a => ToStatus (Either a b) where
type Val (Either a b) = b
toStatus (Left e) = Left (500, "Server Error: " <> show e)
toStatus (Right v) = Right v
instance ToStatus String where
type Val String = ()
toStatus "200 Success" = Right ()
toStatus err = Left (500, err)
因为我没有很好地表达这个问题,所以我跳上#haskell。 问题是,它不能改变任何a
产生这样的val
。 事实证明, ToJSON
与这个问题无关。
这个工程:请注意,我改变toStatus
是a val
,而不是a
,而实例去除类型变量。
class ToStatus a where
toStatus :: a val -> Either (Int, String) val
instance ToStatus Maybe where
toStatus Nothing = Left (404, "Not Found")
toStatus (Just v) = Right v
instance Show a => ToStatus (Either a) where
toStatus (Left a) = Left (500, "Server Error: " <> show a)
toStatus (Right v) = Right v
链接地址: http://www.djcxy.com/p/43533.html