Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 922
John Walker Avatar asked Dec 03 '25 15:12

John Walker


1 Answers

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
like image 86
John Walker Avatar answered Dec 06 '25 06:12

John Walker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!