在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
我如何编写一个类型类(或类似效果的东西),这样我可以在“可能”和“可能”中概括“违约”的概念?
像
这样的东西class Defaultable ???? where
def ∷ a b → b → b
答案 0 :(得分:3)
原来是围绕为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