John Walker
John Walker

Reputation: 543

How can I generalise defaulting across Maybe and Either?

In Haskell, if I have two functions like this:

defEither ∷   Either l r → r → r
defEither  eith defVal = either (const defVal) id eith

and

defMaybe ∷   Maybe a → a → a
defMaybe m d = fromMaybe d m

How do I write a type class (or something to similar effect) such that I can generalise the concept of "defaultable" across both Either and Maybe?

Something like

class Defaultable ???? where
  def ∷  a b → b → b

Upvotes: 3

Views: 127

Answers (1)

John Walker
John Walker

Reputation: 543

Turns out it was the syntax around creating the instance for Either that was confusing me.

Here is what I finished up with:

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

And some tests

def (Just 1) 2
>> 1

def Nothing 2
>> 2

def (Right 2) 5
>> 2

def (Left 3) 5
>> 5

def (Left "Arrghh") 5
>> 5

Upvotes: 3

Related Questions