在Haskell中,如果我有两个这样的功能:
defEither ∷ Either l r → r → r
defEither eith defVal = either (const defVal) id eith
和
defMaybe ∷ Maybe a → a → a
defMaybe m d = fromMaybe d m
如何编写类型类(或具有类似效果的类型),以便可以在Either和Maybe上推广“默认”的概念?
就像是
class Defaultable ???? where
def ∷ a b → b → b
原来,围绕为Either创建实例的语法使我感到困惑。
这是我完成的:
class Defaultable a where
def ∷ a b → b → b
instance Defaultable (Either m) where
def e d = either (const d) id e
instance Defaultable Maybe where
def m d = fromMaybe d m
和一些测试
def (Just 1) 2
>> 1
def Nothing 2
>> 2
def (Right 2) 5
>> 2
def (Left 3) 5
>> 5
def (Left "Arrghh") 5
>> 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句